c# List转DataTable

将List转成DataTable;

1、定义要导出的字段名字和实体字段名字:

1
2
3
4
5
6
7
public Tuple<string, string> GetDataMergeTitle()
{
    string title = "会员号,姓名,身份证信息,配偶名称,配偶身份证信息,资格,留座,资格2,留座2,手机,类型";
    string field = "MelaId,CustomerName,PurchaserIDNumber,SpouseName,SpouseIDNumber,QualificationOne,ReserveSeatOne,QualificationTwo,ReserveSeatTwo,PhoneNumber,Type";
 
    return Tuple.Create(title, field);
}

  

2、List转成DataTable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static DataTable ToDataTable(IList list)
{
    DataTable result = new DataTable();
    if (list.Count > 0)
    {
        PropertyInfo[] propertys = list[0].GetType().GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
            //result.Columns.Add(pi.Name, pi.PropertyType);
 
            Type colType = pi.PropertyType;
            if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
            {
                colType = colType.GetGenericArguments()[0];
            }
            result.Columns.Add(new DataColumn(pi.Name, colType));
        }
        for (int i = 0; i < list.Count; i++)
        {
            ArrayList tempList = new ArrayList();
            foreach (PropertyInfo pi in propertys)
            {
                object obj = pi.GetValue(list[i], null) == null ? DBNull.Value : pi.GetValue(list[i], null);
                tempList.Add(obj);
            }
            object[] array = tempList.ToArray();
            result.LoadDataRow(array, true);
        }
    }
    return result;
 
}

  

3、导出到Excel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
try
{
    Worksheet sheet = wb.Worksheets[0];
    sheet.Name = "年会门票管理";
 
    // 为单元格添加样式
    Aspose.Cells.Style style = wb.CreateStyle();
    style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;  //设置居中
    style.Font.Size = 12;//文字大小
    style.Font.IsBold = true;//粗体
    style.HorizontalAlignment = TextAlignmentType.Center;//文字居中
    int rowIndex = 0;
    for (int i = 0; i < b.Count(); i++)
    {
        sheet.Cells[rowIndex, i].PutValue(b[i]);
        sheet.Cells[rowIndex, i].SetStyle(style);
        sheet.Cells.SetColumnWidth(i, 10);//设置宽度
    }
    for (int i = 0; i < dt.Rows.Count; i++)//遍历DataTable行
    {
        for (int j = 0; j < field.Count(); j++)
        {
            sheet.Cells[i + 1, j].PutValue(dt.Rows[i][field[j]].ToString());
        }
 
    }
}
catch (Exception e)
{
 
}
string filename = strdate + "MeetingTicketManagerExcel.xlsx";
string path = Server.MapPath("~\\UploadFile\\" + filename);
wb.Save(path);
wb = null;
return File(path, "application/vnd.ms-excel", strdate + "MeetingTicketManagerExcel.xlsx");

  

posted @   明&天  阅读(1327)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示