c# List转DataTable

将List转成DataTable;

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

    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

 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:

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 @ 2023-12-01 17:24  明&天  阅读(1621)  评论(0)    收藏  举报