Excel导出采用mvc的ExcelResult继承遇到的问题Npoi导出

时间:2023-03-09 19:34:09
Excel导出采用mvc的ExcelResult继承遇到的问题Npoi导出
 #region 构建Excel文档
//创建Excel文件的对象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.CellStyle style = book.CreateCellStyle();
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
////设置边框格式
style.BorderTop = NPOI.SS.UserModel.CellBorderType.THIN;
style.BorderLeft = NPOI.SS.UserModel.CellBorderType.THIN;
style.BorderRight = NPOI.SS.UserModel.CellBorderType.THIN;
style.BorderBottom = NPOI.SS.UserModel.CellBorderType.THIN; //添加一个sheet
NPOI.SS.UserModel.Sheet sheet1 = book.CreateSheet("Sheet1");
//获取list数据
NPOI.SS.UserModel.Row row1 = sheet1.CreateRow();
SetColcumns(book, sheet1, style, , row1, "编号");
SetColcumns(book, sheet1, style, , row1, "人");
SetColcumns(book, sheet1, style, , row1, "是否本人");
for (int i = ; i < ; i++)
{
sheet1.SetColumnWidth(i, * );
}
//将数据逐步写入sheet1各个行
int num = ;
foreach (var item in cooperates)
{
NPOI.SS.UserModel.Row rowtemp = sheet1.CreateRow(num + ); SetColcumns(book, sheet1, style, , rowtemp, item.ID.ToString());
SetColcumns(book, sheet1, style, , rowtemp, item.UserName);
SetColcumns(book, sheet1, style, , rowtemp, item.IsSelfStrc);
num++;
}
byte[] data = null;
using (MemoryStream ms = new MemoryStream())
{
book.Write(ms);
ms.Flush();
ms.Position = ;
data = ms.GetBuffer();
}
return File(data, "application/vnd.ms-excel", "信息" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
#endregion