62,046
社区成员
发帖
与我相关
我的任务
分享
目前是这样的,list先转datatable,然后Model反射取列名和列宽,最后循环datatable
可以直接循环list吗,我不会反射取list的每个栏位的值
public static MemoryStream DataTableToExcel<T>(DataTable dt) where T : class, new()
{
XSSFWorkbook fileWorkbook = new XSSFWorkbook();
ISheet sheet = fileWorkbook.CreateSheet("Sheet1");
List<int> nonDownList = new List<int>();
List<int> columnWidthList = new List<int>();
List<string> columnNameList = new List<string>();
var type = typeof(T).GetType();
int nonDown = 0;
foreach (var porp in type.GetProperties())
{
nonDown++;
if (porp.IsDefined(typeof(ShowNameAttribute), true))
{
var showNameAttribute = porp.GetCustomAttribute<ShowNameAttribute>();
columnNameList.Add(showNameAttribute.ShowName);
var columnWidthAttribute = porp.GetCustomAttribute<ColumnWidthAttribute>();
var number = columnWidthAttribute == null ? columnWidth : columnWidthAttribute.Number;
columnWidthList.Add(number);
}
else
{
nonDownList.Add(nonDown);
}
}
//表头
IRow row = sheet.CreateRow(0);
for (int i = 0; i < columnNameList.Count; i++)
{
ICell cell = row.CreateCell(i); //創建單元格
cell.SetCellValue(columnNameList[i]); //表頭賦值
sheet.SetColumnWidth(i, columnWidthList[i]); //表頭寬度
cell.CellStyle = excelStyle.CellHeadStyle; //表頭樣式
row.Height = 30 * 20; //行高为30
}
//数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!nonDownList.Contains(j))
{
ICell cell = row1.CreateCell(j);
string drValue = dt.Rows[i][j].ToString();
CellStyle(cell, dt.Columns[j].DataType.ToString(), drValue);
}
}
}
//转为字节数组
using (MemoryStream ms = new MemoryStream())
{
fileWorkbook.Write(ms);
ms.Flush();
return ms;
}
}
var type = default(T).GetType();
foreach (var porp in type.GetProperties())
{
if(porp.IsDefined(typeof(ShowNameAttribute), true))
{
var showNameAttribute = porp.GetCustomAttribute<ShowNameAttribute>();
showNameList.Add(showNameAttribute.ShowName);
var columnWidthAttribute = porp.GetCustomAttribute<ColumnWidthAttribute>();
var number = columnWidthAttribute == null ? columnWidth : columnWidthAttribute.Number;
columnWidthList.Add(number);
}
}
//数据
for (int i = 0; i < list.Count; i++)
{
int j = 0;
IRow row1 = sheet.CreateRow(i + 1);
foreach (var porp in type.GetProperties())
{
if (porp.IsDefined(typeof(ShowNameAttribute), true))
{
j++;
ICell cell = row1.CreateCell(j);
string drValue = porp.GetValue(default(T)).ToString();
CellStyle(cell, porp.PropertyType.Name, drValue);
}
}
}