使用NPOI导出Excel文件

时间:2023-03-09 04:48:13
使用NPOI导出Excel文件

使用NPOI导出Excel文件,本实例使用了ASP.NET MVC。

1、使用NPOI导出Excel文件

实例:导出商品列表。

要求:1、通过NPOI导出导出商品列表信息;

2、使用Excel函数计算商品总金额;

在Controllers控制器目录中创建ExportController.cs控制器

  1. using System.IO;
  2. using NPOI;
  3. using NPOI.POIFS;
  4. using NPOI.HSSF;
  5. using NPOI.Util;
  6. using NPOI.HSSF.UserModel;
  7. using NPOI.HPSF;
  8. using NPOI.SS.UserModel;
  9. using NPOI.SS.Util;
  10. using NPOI.HSSF.Util;
  1. /// <summary>
  2. /// 导出商品列表
  3. /// </summary>
  4. public FileResult ExportProduct()
  5. {
  6. //创建一个新的xls文件
  7. HSSFWorkbook workbook = new HSSFWorkbook();
  8. //创建DocumentSummaryInformation(选填)
  9. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  10. dsi.Company = "深圳市电子商务有限公司";
  11. dsi.Category = "报表";
  12. //创建SummaryInformation(选填)
  13. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  14. si.Subject = "商品列表";
  15. si.Title = "商品列表导出";
  16. si.Author = "Kevin Pan";
  17. //把创建好的对象赋给Workbook
  18. workbook.DocumentSummaryInformation = dsi;
  19. workbook.SummaryInformation = si;
  20. //创建一个Sheet
  21. ISheet sheet = workbook.CreateSheet("Sheet1");
  22. sheet.DefaultRowHeight = 300;
  23. //创建标题
  24. IRow rowTitle = sheet.CreateRow(0);
  25. rowTitle.Height = 500;
  26. ICellStyle styleTitle = workbook.CreateCellStyle();
  27. styleTitle.Alignment = HorizontalAlignment.Center;
  28. styleTitle.VerticalAlignment = VerticalAlignment.Center;
  29. IFont fontTitle = workbook.CreateFont();
  30. fontTitle.FontName = "宋体";
  31. fontTitle.FontHeightInPoints = 18;
  32. styleTitle.SetFont(fontTitle);
  33. ICell cellTitle = rowTitle.CreateCell(0);
  34. cellTitle.SetCellValue("商品列表");
  35. cellTitle.CellStyle = styleTitle;
  36. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 5));  //合并单元格
  37. //创建表格样式
  38. IFont font = workbook.CreateFont();
  39. font.FontName = "宋体";
  40. font.FontHeightInPoints = 10;
  41. ICellStyle style = workbook.CreateCellStyle(); ;
  42. style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  43. style.BottomBorderColor = HSSFColor.Black.Index;
  44. style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  45. style.LeftBorderColor = HSSFColor.Black.Index;
  46. style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  47. style.RightBorderColor = HSSFColor.Black.Index;
  48. style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  49. style.TopBorderColor = HSSFColor.Black.Index;
  50. style.Alignment = HorizontalAlignment.Center;
  51. style.SetFont(font);
  52. //创建表头
  53. IRow rowHead = sheet.CreateRow(1);
  54. rowHead.CreateCell(0).SetCellValue("序号");
  55. rowHead.GetCell(0).CellStyle = style;
  56. sheet.SetColumnWidth(0, 256 * 5);
  57. rowHead.CreateCell(1).SetCellValue("商品名称");
  58. rowHead.GetCell(1).CellStyle = style;
  59. sheet.SetColumnWidth(1, 256 * 25);
  60. rowHead.CreateCell(2).SetCellValue("商品品牌");
  61. rowHead.GetCell(2).CellStyle = style;
  62. sheet.SetColumnWidth(2, 256 * 20);
  63. rowHead.CreateCell(3).SetCellValue("商品价格");
  64. rowHead.GetCell(3).CellStyle = style;
  65. sheet.SetColumnWidth(3, 256 * 15);
  66. rowHead.CreateCell(4).SetCellValue("数量");
  67. rowHead.GetCell(4).CellStyle = style;
  68. sheet.SetColumnWidth(3, 256 * 10);
  69. rowHead.CreateCell(5).SetCellValue("总金额");
  70. rowHead.GetCell(5).CellStyle = style;
  71. sheet.SetColumnWidth(3, 256 * 15);
  72. //获取商品列表数据
  73. List<ProductModel> dataList = GetProductList();
  74. //绑定表内容
  75. int rowindex = 2;
  76. int xh = 1;
  77. foreach (var item in dataList)
  78. {
  79. IRow rowContent = sheet.CreateRow(rowindex);
  80. rowContent.CreateCell(0).SetCellValue(xh);
  81. rowContent.GetCell(0).CellStyle = style;
  82. rowContent.CreateCell(1).SetCellValue(item.ProductName);
  83. rowContent.GetCell(1).CellStyle = style;
  84. rowContent.CreateCell(2).SetCellValue(item.ProductBrand);
  85. rowContent.GetCell(2).CellStyle = style;
  86. rowContent.CreateCell(3).SetCellValue(item.ProductPrice.ToString());
  87. rowContent.GetCell(3).CellStyle = style;
  88. rowContent.CreateCell(4).SetCellValue(item.Quantity.ToString());
  89. rowContent.GetCell(4).CellStyle = style;
  90. //设置函数,计算总金额
  91. rowContent.CreateCell(5).SetCellFormula(String.Format("$D{0}*$E{0}", rowindex+1));
  92. rowContent.GetCell(5).CellStyle = style;
  93. rowindex++;
  94. xh++;
  95. }
  96. //输出
  97. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  98. workbook.Write(ms);
  99. ms.Seek(0, SeekOrigin.Begin);
  100. return File(ms, "application/vnd.ms-excel", "商品列表.xls");
  101. }

2、基于.xls模板导出Excel文件

实例:基于.xls模板导出订单信息(如图 1)

要求:1、使用基于.xls模板导出订单信息;

2、使用Excel函数计算订单和商品的总金额;

使用NPOI导出Excel文件

图 1 基于.xls模板导出订单信息

  1. /// <summary>
  2. /// 导出订单信息
  3. /// </summary>
  4. public FileResult ExportOrder()
  5. {
  6. //获取订单信息
  7. OrderModel order = GetOrderInfo();
  8. //获取Excel模板
  9. string fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/Template/order.xls";
  10. FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  11. //通过模板创建一个xls文件
  12. HSSFWorkbook workbook = new HSSFWorkbook(file);
  13. //获取Sheet
  14. ISheet sheet = workbook.GetSheet("Sheet1");
  15. //导出订单信息
  16. sheet.GetRow(1).CreateCell(1).SetCellValue(order.OrderNo);
  17. sheet.GetRow(1).CreateCell(3).SetCellValue(order.OrderTime.ToString("yyyy-MM-dd HH:mm:ss"));
  18. sheet.GetRow(1).CreateCell(5).SetCellFormula("SUM(F6:F100)"); //设置函数,计算订单总金额
  19. sheet.GetRow(2).CreateCell(1).SetCellValue(order.CustomName);
  20. sheet.GetRow(2).CreateCell(3).SetCellValue(order.CustomAddress);
  21. //导出产品列表
  22. if (order.ProductList != null && order.ProductList.Count > 0)
  23. {
  24. //创建表头
  25. IRow rowHead = sheet.CreateRow(4);
  26. rowHead.CreateCell(0).SetCellValue("序号");
  27. sheet.SetColumnWidth(0, 256 * 15);
  28. rowHead.CreateCell(1).SetCellValue("商品名称");
  29. sheet.SetColumnWidth(1, 256 * 25);
  30. rowHead.CreateCell(2).SetCellValue("商品品牌");
  31. sheet.SetColumnWidth(2, 256 * 20);
  32. rowHead.CreateCell(3).SetCellValue("商品价格");
  33. sheet.SetColumnWidth(3, 256 * 15);
  34. rowHead.CreateCell(4).SetCellValue("数量");
  35. sheet.SetColumnWidth(3, 256 * 10);
  36. rowHead.CreateCell(5).SetCellValue("总金额");
  37. sheet.SetColumnWidth(3, 256 * 15);
  38. //绑定表内容
  39. int rowindex = 5;
  40. int xh = 1;
  41. foreach (var item in order.ProductList)
  42. {
  43. IRow rowContent = sheet.CreateRow(rowindex);
  44. rowContent.CreateCell(0).SetCellValue(xh);
  45. rowContent.CreateCell(1).SetCellValue(item.ProductName);
  46. rowContent.CreateCell(2).SetCellValue(item.ProductBrand);
  47. rowContent.CreateCell(3).SetCellValue(item.ProductPrice.ToString());
  48. rowContent.CreateCell(4).SetCellValue(item.Quantity.ToString());
  49. rowContent.CreateCell(5).SetCellFormula(String.Format("$D{0}*$E{0}", rowindex + 1));  //设置函数,计算总金额
  50. rowindex++;
  51. xh++;
  52. }
  53. }
  54. //输出
  55. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  56. workbook.Write(ms);
  57. ms.Seek(0, SeekOrigin.Begin);
  58. return File(ms, "application/vnd.ms-excel", "订单信息.xls");
  59. }

3、其他代码

3.1 实体类

在Models模型目录中创建ProductModel.cs和OrderModel.cs实体类

  1. /// <summary>
  2. /// 商品信息实体类
  3. /// </summary>
  4. public class ProductModel
  5. {
  6. /// <summary>
  7. /// 商品名称
  8. /// </summary>
  9. public string ProductName { get; set; }
  10. /// <summary>
  11. /// 商品品牌
  12. /// </summary>
  13. public string ProductBrand { get; set; }
  14. /// <summary>
  15. /// 商品价格
  16. /// </summary>
  17. public decimal ProductPrice { get; set; }
  18. /// <summary>
  19. /// 数量
  20. /// </summary>
  21. public int Quantity { get; set; }
  22. }
  1. /// <summary>
  2. /// 订单信息实体类
  3. /// </summary>
  4. public class OrderModel
  5. {
  6. /// <summary>
  7. /// 订单编号
  8. /// </summary>
  9. public string OrderNo { get; set; }
  10. /// <summary>
  11. /// 下单时间
  12. /// </summary>
  13. public DateTime OrderTime { get; set; }
  14. /// <summary>
  15. /// 总金额
  16. /// </summary>
  17. public decimal Amount { get; set; }
  18. /// <summary>
  19. /// 客户名称
  20. /// </summary>
  21. public string CustomName { get; set; }
  22. /// <summary>
  23. /// 客户地址
  24. /// </summary>
  25. public string CustomAddress { get; set; }
  26. /// <summary>
  27. /// 商品列表
  28. /// </summary>
  29. public List<ProductModel> ProductList { get; set; }
  30. }

3.2 获取商品和订单数据

  1. /// <summary>
  2. /// 获取商品列表
  3. /// </summary>
  4. public List<ProductModel> GetProductList()
  5. {
  6. List<ProductModel> productList = new List<ProductModel>();
  7. ProductModel product1 = new ProductModel(){
  8. ProductName = "苹果IPhone6手机",
  9. ProductBrand = "苹果",
  10. ProductPrice = 4999,
  11. Quantity = 4
  12. };
  13. ProductModel product2 = new ProductModel()
  14. {
  15. ProductName = "三星智能手机",
  16. ProductBrand = "三星",
  17. ProductPrice = 3800,
  18. Quantity = 3
  19. };
  20. ProductModel product3 = new ProductModel()
  21. {
  22. ProductName = "松下液晶电视机",
  23. ProductBrand = "松下",
  24. ProductPrice = 3800,
  25. Quantity = 2
  26. };
  27. productList.Add(product1);
  28. productList.Add(product2);
  29. productList.Add(product3);
  30. return productList;
  31. }
  32. /// <summary>
  33. /// 获取订单信息
  34. /// </summary>
  35. public OrderModel GetOrderInfo()
  36. {
  37. OrderModel order = new OrderModel() {
  38. OrderNo = "P20140929001",
  39. OrderTime = DateTime.Now,
  40. CustomName = "张三",
  41. CustomAddress = "广东省深圳市罗湖区",
  42. ProductList = GetProductList()
  43. };
  44. return order;
  45. }

3.3 视图

在Views视图目录中创建Index.cshtml

  1. <h2>使用NPOI生成Excel文件</h2>
  2. <a href="@Url.Action("ExportProduct","Export")">导出商品</a>
  3. <a href="@Url.Action("ExportOrder","Export")">导出订单</a>