NPOI+反射 实现快速导出

时间:2023-03-09 08:45:36
NPOI+反射 实现快速导出

只是觉得这样很方便 记录一下

公司有封装的方法,不过是查出的Table类型,每次用的时候很都很烦,处理数据也不方便,最主要的是我也没耐心去看,反正在我看来很麻烦,用的时候很头疼。还是习惯通过Model List来处理数据,可以利用Model Class属性来处理数据格式等等


            var orders=GetOrders();//获取订单列表
            //Excel表头            
string[] headerTemp = { "订单号", "下单时间", "订单状态", "店铺名称", "商品名称"};
//对应的Model Class属性
string[] propertyNameTemp = { "OrderId", "OrderDate", "OrderStatusString", "StoreName", "ProductName"};
#region excel简单样式设置
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
ICellStyle othercolstyle = hssfworkbook.CreateCellStyle();
IFont othercolfont = hssfworkbook.CreateFont();
othercolfont.FontName = "微软雅黑";
othercolfont.FontHeightInPoints = ;
othercolstyle.SetFont(othercolfont);
othercolstyle.VerticalAlignment = VerticalAlignment.Center;
othercolstyle.Alignment = HorizontalAlignment.Center;
#endregion for (int i = ; i <= orders.Count; i++)
{
IRow row = sheet1.CreateRow(i);
row.Height = * ;
for (int j = ; j < headerTemp.Length; j++)
{
ICell cell = row.CreateCell(j);
cell.CellStyle = othercolstyle;
sheet1.SetColumnWidth(j, * );
if (i == )
{
              //第一行设置表头
cell.SetCellValue(headerTemp[j]);
}
else
{
Type temp = orders[i - ].GetType();
PropertyInfo propertyInfo = temp.GetProperty(propertyNameTemp[j]);
object pvalue = propertyInfo.GetValue(orders[i - ], null);
cell.SetCellValue(pvalue == null ? "" : pvalue.ToString());
}
}
}
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
hssfworkbook.Write(ms);
ms.Seek(, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", string.Format("{0}.xls", DateTime.Now)); //上面代码 return File为.net mvc中返回方式
//ashx或aspx页面最后返回方式

//写入流
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);


if (file != null)
{
// 写入到客户端
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpContext.Current.Server.UrlEncode("竞猜用户.xlsx")));
Response.BinaryWrite(file.ToArray());
}

 

每次只需要设置excel表头和对应的Model属性就可以,反射那部分不用动。

一般像订单状态查出来是int类型的枚举值,可以在Model里扩展枚举属性OrderStatusString

public string OrderStatusString
{
get{return 对应的订单状态枚举;}
}