首页 > 代码库 > mvc4 用NPOI导出Excel

mvc4 用NPOI导出Excel

第一次做数据导出Excel,刚看到这个的时候,首先想到的就是新建一个excel的文件,然后将它下载,后来询问别人,他们都推荐使用NPOI,发现这个很好用,就用博客记录一下

1、引用NPOI包

2、导出Excel

/// <summary>
/// 导出Excel
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
public FileResult DownExcel(FormCollection collection)
{
var supplierName = collection["Supplier_SelectSupplierName"];//页面查询条件
var goodsName = collection["Supplier_SelectGoodsName"];//页面查询条件
var list = ServiceClients.SupplierClient.SelectBandingSupplier(_shopid.ShopID, goodsName, supplierName);//数据源
var wb = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = wb.CreateSheet("Sheet1");//创建sheet
NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);//先创建标题那一行
row.CreateCell(0).SetCellValue("商品名称");//创建单元格
row.CreateCell(1).SetCellValue("供应商");
row.CreateCell(2).SetCellValue("价格");
for (int i = 0; i < list.Data.ToList().Count; i++)//填充数据
{
NPOI.SS.UserModel.IRow rowMap = sheet.CreateRow(i + 1);
rowMap.CreateCell(0).SetCellValue(list.Data.ToList()[i].GoodsName);
rowMap.CreateCell(1).SetCellValue(list.Data.ToList()[i].SupplierName);
rowMap.CreateCell(2).SetCellValue(list.Data.ToList()[i].Price.ToString(CultureInfo.InvariantCulture));
}
var ms = new System.IO.MemoryStream();
wb.Write(ms);
ms.Seek(0, System.IO.SeekOrigin.Begin);
var date = DateTime.Now.ToString("yyyyMMddHHmmss");
return File(ms, "application/vnd.ms-excel", "外购商品绑定" + date + ".xls");//输出
}

mvc4 用NPOI导出Excel