下面我来讲解一下怎样用Session来导出Excel,其实代码很简单,原理也很简单,我说这个主要是代码简单简短方便。
首先,引用NPOI.
接下来看核心代码,如下图。
public ActionResult printjingxiaocuntongji()//打印进销存统计
{
if (Session["listSession2"] != null)
{
List<ShangPingXinXi> listSelect = Session["listSession2"] as List<ShangPingXinXi>;
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet();
//第三步:Excel表头设置
#region Excel表头设置
//给sheet添加第一行的头部标题
NPOI.SS.UserModel.IRow row1 = sheet.CreateRow(0);//创建行
row1.CreateCell(0).SetCellValue("商品编码(条码)");
row1.CreateCell(1).SetCellValue("商品名称");
row1.CreateCell(2).SetCellValue("款号");
row1.CreateCell(3).SetCellValue("颜色");
row1.CreateCell(4).SetCellValue("尺码");
row1.CreateCell(5).SetCellValue("吊牌价");
row1.CreateCell(6).SetCellValue("单位");
row1.CreateCell(7).SetCellValue("本期进货数量");
row1.CreateCell(8).SetCellValue("本期进货金额");
row1.CreateCell(9).SetCellValue("本期退货数量");
row1.CreateCell(10).SetCellValue("本期退货金额");
row1.CreateCell(11).SetCellValue("本期销售数量");
row1.CreateCell(12).SetCellValue("本期销售金额");
row1.CreateCell(13).SetCellValue("本期库存数量");
row1.CreateCell(14).SetCellValue("本期库存金额");
#region 给sheet的每行添加数据
for (int i = 0; i < listSelect.Count; i++)
{
NPOI.SS.UserModel.IRow row = sheet.CreateRow(i + 1);
row.CreateCell(0).SetCellValue(listSelect[i].Commoditycode);
row.CreateCell(1).SetCellValue(listSelect[i].commodityname);
row.CreateCell(2).SetCellValue(listSelect[i].stylenumber);
row.CreateCell(3).SetCellValue(listSelect[i].ColourMC);
row.CreateCell(4).SetCellValue(listSelect[i].YardageMC);
row.CreateCell(5).SetCellValue(listSelect[i].tagprice.ToString());
row.CreateCell(6).SetCellValue(listSelect[i].UnitMC);
row.CreateCell(7).SetCellValue(listSelect[i].Stockamount.ToString());
row.CreateCell(8).SetCellValue(listSelect[i].jinhuozonjine.ToString());
row.CreateCell(9).SetCellValue(listSelect[i].SHULIANG.ToString());
row.CreateCell(10).SetCellValue(listSelect[i].tuihuozonjine.ToString());
row.CreateCell(11).SetCellValue(listSelect[i].Amount.ToString());
row.CreateCell(12).SetCellValue(listSelect[i].xiaoshoushuje.ToString());
row.CreateCell(13).SetCellValue(listSelect[i].kucunshu.ToString());
row.CreateCell(14).SetCellValue(listSelect[i].kucunjine.ToString());
}
MemoryStream BookStream = new MemoryStream();//定义文件流
book.Write(BookStream);//将工作薄写入文件流
//输出之前调用Seek(偏移量,游标位置)方法:获取文件流的长度
BookStream.Seek(0, SeekOrigin.Begin);
//输出的文件名称
string filename = "进-销-存统计分析" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
return File(BookStream, "application/vnd.ms-excel", filename); // 文件类型/文件名称/
#endregion
#endregion
}
else
{
return Content("数据异常,请确认是否成功查询数据");
}
}
那么看了代码之后对你有什么启发了吗?如果有就动动你的小手指去尝试一下吧。