开发工具与关键技术:vs与mvc js
作者:执~漠
撰写时间:2020年8月8日星期六
导出数据前要引用NPOI插件到项目中,导出前要提前构建好模板。
第一先检查模板是否存在,不存在导不出数据的
// Server.MapPath 将相对的路径转为实际的物理路径
string templatePath = Server.MapPath("~/Document/ARDataTemplate.xls");
用Server.MapPath来将相对路径转为实际的物理路径
if (!System.IO.File.Exists(templatePath))
{
//如果不存在,就返回失败信息
return Content("导出失败,请联系网站管理员");
}
用System.IO.File.Exists来确定指定的文件是否存在。不存在返回导出失败,请联系网站管理员
FileStream templateStream = System.IO.File.Open(templatePath, FileMode.Open);
如果存在就声明templateStream这个变量来表示使用System.IO.File.Open打开模板文件
//=2.2-使用NPOI打开模板Excel 得到一个工作簿
NPOI.HSSF.UserModel.HSSFWorkbook excelBookTemplate = new NPOI.HSSF.UserModel.HSSFWorkbook(templateStream);
得到工作簿后,工作簿里面可以有很多工作表,获取到第一个工资表
NPOI.SS.UserModel.ISheet sheet = excelBookTemplate.GetSheetAt(0);
//==4-设置标题,如果筛选时间段不为空就拼接上筛选时间段
if (!string.IsNullOrEmpty(startEndDate))
{
//提取模板标题
NPOI.SS.UserModel.IRow rowTitle = sheet.GetRow(0);
rowTitle.GetCell(0).SetCellValue("订单数据 " + startEndDate);
}
如果导出的数据的值不为空时就设置标题为第一行sheet.GetRow(0)
然后就设置数据单元格的样式
//水平垂直居中对齐
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
//设置边框为实线
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
设置完一个单元格的样式后,开始给单元格赋值
//遍历查询出的数据 填充Excel单元格
for (int i = 0; i < list.Count(); i++)
{
NPOI.SS.UserModel.IRow row = sheet.CreateRow(index); ;//给sheet添加一行
row.Height = 22 * 20;//设置行高
//设置单元格数据
row.CreateCell(0).SetCellValue(i + 1);//序号
row.CreateCell(1).SetCellValue(list[i].orderNo);//订单号
row.CreateCell(2).SetCellValue(list[i].payTime.ToString());//支付日期
row.CreateCell(3).SetCellValue(list[i].totalPrice.ToString());//总金额
row.CreateCell(4).SetCellValue(list[i].agencyFee.ToString());//代理费
row.CreateCell(5).SetCellValue(list[i].payMoney.ToString());//实付金额
row.CreateCell(6).SetCellValue(list[i].userGroup.ToString());//组号
row.CreateCell(7).SetCellValue(list[i].jobNumber.ToString());//工号
row.CreateCell(8).SetCellValue(list[i].PNR.ToString());//PNR
//设置单元格样式
for (int j = 0; j < row.Cells.Count; j++)
{
row.GetCell(j).CellStyle = style;
}
index++;
}
给你需要的数据赋值完后,以流的方式返回
string fileName = "订单信息" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + ".xls";
//把Excel转化为流,输出
MemoryStream BookStream = new MemoryStream();//定义内存流
excelBookTemplate.Write(BookStream);//将工作薄写入内存流
最后输出文件
/*参数:File(fileStream要发送到响应的流,
contentType内容类型(MIME 类型),
fileDownloadName浏览器中显示的文件下载对话框内要使用的文件名。) */
return File(BookStream, "application/vnd.ms-excel", fileName);