当前位置:网站首页>使用NPOI导出Excel文件
使用NPOI导出Excel文件
2022-07-02 16:16:00 【全栈程序员站长】
大家好,又见面了,我是你们的朋友全栈君。
使用NPOI导出Excel文件,本实例使用了ASP.NET MVC。
1、使用NPOI导出Excel文件
实例:导出商品列表。
要求:1、通过NPOI导出导出商品列表信息;
2、使用Excel函数计算商品总金额;
在Controllers控制器目录中创建ExportController.cs控制器
using System.IO;
using NPOI;
using NPOI.POIFS;
using NPOI.HSSF;
using NPOI.Util;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.HSSF.Util;
/// <summary>
/// 导出商品列表
/// </summary>
public FileResult ExportProduct()
{
//创建一个新的xls文件
HSSFWorkbook workbook = new HSSFWorkbook();
//创建DocumentSummaryInformation(选填)
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "深圳市电子商务有限公司";
dsi.Category = "报表";
//创建SummaryInformation(选填)
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "商品列表";
si.Title = "商品列表导出";
si.Author = "Kevin Pan";
//把创建好的对象赋给Workbook
workbook.DocumentSummaryInformation = dsi;
workbook.SummaryInformation = si;
//创建一个Sheet
ISheet sheet = workbook.CreateSheet("Sheet1");
sheet.DefaultRowHeight = 300;
//创建标题
IRow rowTitle = sheet.CreateRow(0);
rowTitle.Height = 500;
ICellStyle styleTitle = workbook.CreateCellStyle();
styleTitle.Alignment = HorizontalAlignment.Center;
styleTitle.VerticalAlignment = VerticalAlignment.Center;
IFont fontTitle = workbook.CreateFont();
fontTitle.FontName = "宋体";
fontTitle.FontHeightInPoints = 18;
styleTitle.SetFont(fontTitle);
ICell cellTitle = rowTitle.CreateCell(0);
cellTitle.SetCellValue("商品列表");
cellTitle.CellStyle = styleTitle;
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 5)); //合并单元格
//创建表格样式
IFont font = workbook.CreateFont();
font.FontName = "宋体";
font.FontHeightInPoints = 10;
ICellStyle style = workbook.CreateCellStyle(); ;
style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style.BottomBorderColor = HSSFColor.Black.Index;
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style.LeftBorderColor = HSSFColor.Black.Index;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style.RightBorderColor = HSSFColor.Black.Index;
style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style.TopBorderColor = HSSFColor.Black.Index;
style.Alignment = HorizontalAlignment.Center;
style.SetFont(font);
//创建表头
IRow rowHead = sheet.CreateRow(1);
rowHead.CreateCell(0).SetCellValue("序号");
rowHead.GetCell(0).CellStyle = style;
sheet.SetColumnWidth(0, 256 * 5);
rowHead.CreateCell(1).SetCellValue("商品名称");
rowHead.GetCell(1).CellStyle = style;
sheet.SetColumnWidth(1, 256 * 25);
rowHead.CreateCell(2).SetCellValue("商品品牌");
rowHead.GetCell(2).CellStyle = style;
sheet.SetColumnWidth(2, 256 * 20);
rowHead.CreateCell(3).SetCellValue("商品价格");
rowHead.GetCell(3).CellStyle = style;
sheet.SetColumnWidth(3, 256 * 15);
rowHead.CreateCell(4).SetCellValue("数量");
rowHead.GetCell(4).CellStyle = style;
sheet.SetColumnWidth(3, 256 * 10);
rowHead.CreateCell(5).SetCellValue("总金额");
rowHead.GetCell(5).CellStyle = style;
sheet.SetColumnWidth(3, 256 * 15);
//获取商品列表数据
List<ProductModel> dataList = GetProductList();
//绑定表内容
int rowindex = 2;
int xh = 1;
foreach (var item in dataList)
{
IRow rowContent = sheet.CreateRow(rowindex);
rowContent.CreateCell(0).SetCellValue(xh);
rowContent.GetCell(0).CellStyle = style;
rowContent.CreateCell(1).SetCellValue(item.ProductName);
rowContent.GetCell(1).CellStyle = style;
rowContent.CreateCell(2).SetCellValue(item.ProductBrand);
rowContent.GetCell(2).CellStyle = style;
rowContent.CreateCell(3).SetCellValue(item.ProductPrice.ToString());
rowContent.GetCell(3).CellStyle = style;
rowContent.CreateCell(4).SetCellValue(item.Quantity.ToString());
rowContent.GetCell(4).CellStyle = style;
//设置函数,计算总金额
rowContent.CreateCell(5).SetCellFormula(String.Format("$D{0}*$E{0}", rowindex+1));
rowContent.GetCell(5).CellStyle = style;
rowindex++;
xh++;
}
//输出
System.IO.MemoryStream ms = new System.IO.MemoryStream();
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", "商品列表.xls");
}
2、基于.xls模板导出Excel文件
实例:基于.xls模板导出订单信息(如图 1)
要求:1、使用基于.xls模板导出订单信息;
2、使用Excel函数计算订单和商品的总金额;
图 1 基于.xls模板导出订单信息
/// <summary>
/// 导出订单信息
/// </summary>
public FileResult ExportOrder()
{
//获取订单信息
OrderModel order = GetOrderInfo();
//获取Excel模板
string fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/Template/order.xls";
FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
//通过模板创建一个xls文件
HSSFWorkbook workbook = new HSSFWorkbook(file);
//获取Sheet
ISheet sheet = workbook.GetSheet("Sheet1");
//导出订单信息
sheet.GetRow(1).CreateCell(1).SetCellValue(order.OrderNo);
sheet.GetRow(1).CreateCell(3).SetCellValue(order.OrderTime.ToString("yyyy-MM-dd HH:mm:ss"));
sheet.GetRow(1).CreateCell(5).SetCellFormula("SUM(F6:F100)"); //设置函数,计算订单总金额
sheet.GetRow(2).CreateCell(1).SetCellValue(order.CustomName);
sheet.GetRow(2).CreateCell(3).SetCellValue(order.CustomAddress);
//导出产品列表
if (order.ProductList != null && order.ProductList.Count > 0)
{
//创建表头
IRow rowHead = sheet.CreateRow(4);
rowHead.CreateCell(0).SetCellValue("序号");
sheet.SetColumnWidth(0, 256 * 15);
rowHead.CreateCell(1).SetCellValue("商品名称");
sheet.SetColumnWidth(1, 256 * 25);
rowHead.CreateCell(2).SetCellValue("商品品牌");
sheet.SetColumnWidth(2, 256 * 20);
rowHead.CreateCell(3).SetCellValue("商品价格");
sheet.SetColumnWidth(3, 256 * 15);
rowHead.CreateCell(4).SetCellValue("数量");
sheet.SetColumnWidth(3, 256 * 10);
rowHead.CreateCell(5).SetCellValue("总金额");
sheet.SetColumnWidth(3, 256 * 15);
//绑定表内容
int rowindex = 5;
int xh = 1;
foreach (var item in order.ProductList)
{
IRow rowContent = sheet.CreateRow(rowindex);
rowContent.CreateCell(0).SetCellValue(xh);
rowContent.CreateCell(1).SetCellValue(item.ProductName);
rowContent.CreateCell(2).SetCellValue(item.ProductBrand);
rowContent.CreateCell(3).SetCellValue(item.ProductPrice.ToString());
rowContent.CreateCell(4).SetCellValue(item.Quantity.ToString());
rowContent.CreateCell(5).SetCellFormula(String.Format("$D{0}*$E{0}", rowindex + 1)); //设置函数,计算总金额
rowindex++;
xh++;
}
}
//输出
System.IO.MemoryStream ms = new System.IO.MemoryStream();
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", "订单信息.xls");
}
3、其他代码
3.1 实体类
在Models模型目录中创建ProductModel.cs和OrderModel.cs实体类
/// <summary>
/// 商品信息实体类
/// </summary>
public class ProductModel
{
/// <summary>
/// 商品名称
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// 商品品牌
/// </summary>
public string ProductBrand { get; set; }
/// <summary>
/// 商品价格
/// </summary>
public decimal ProductPrice { get; set; }
/// <summary>
/// 数量
/// </summary>
public int Quantity { get; set; }
}
/// <summary>
/// 订单信息实体类
/// </summary>
public class OrderModel
{
/// <summary>
/// 订单编号
/// </summary>
public string OrderNo { get; set; }
/// <summary>
/// 下单时间
/// </summary>
public DateTime OrderTime { get; set; }
/// <summary>
/// 总金额
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// 客户名称
/// </summary>
public string CustomName { get; set; }
/// <summary>
/// 客户地址
/// </summary>
public string CustomAddress { get; set; }
/// <summary>
/// 商品列表
/// </summary>
public List<ProductModel> ProductList { get; set; }
}
3.2 获取商品和订单数据
/// <summary>
/// 获取商品列表
/// </summary>
public List<ProductModel> GetProductList()
{
List<ProductModel> productList = new List<ProductModel>();
ProductModel product1 = new ProductModel(){
ProductName = "苹果IPhone6手机",
ProductBrand = "苹果",
ProductPrice = 4999,
Quantity = 4
};
ProductModel product2 = new ProductModel()
{
ProductName = "三星智能手机",
ProductBrand = "三星",
ProductPrice = 3800,
Quantity = 3
};
ProductModel product3 = new ProductModel()
{
ProductName = "松下液晶电视机",
ProductBrand = "松下",
ProductPrice = 3800,
Quantity = 2
};
productList.Add(product1);
productList.Add(product2);
productList.Add(product3);
return productList;
}
/// <summary>
/// 获取订单信息
/// </summary>
public OrderModel GetOrderInfo()
{
OrderModel order = new OrderModel() {
OrderNo = "P20140929001",
OrderTime = DateTime.Now,
CustomName = "张三",
CustomAddress = "广东省深圳市罗湖区",
ProductList = GetProductList()
};
return order;
}
3.3 视图
在Views视图目录中创建Index.cshtml
<h2>使用NPOI生成Excel文件</h2>
<a href="@Url.Action("ExportProduct","Export")">导出商品</a>
<a href="@Url.Action("ExportOrder","Export")">导出订单</a>
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/148244.html原文链接:https://javaforall.cn
边栏推荐
- Easyai notes - deep learning
- MySQL安装与配置
- [nonlinear control theory]7_ High gain and High Frequency
- Redisson high performance redis distributed lock source code analysis
- Wasserstein Slim GAIN with Clipping Penalty(WSGAIN-CP)介绍及代码实现——基于生成对抗网络的缺失数据填补
- 开发一个禁止删除namespace的控制器
- 详解Kubernetes网络模型
- The price is only 40 yuan. Pico development board of raspberry pie is added with WiFi module, and it is out of stock as soon as it comes into the market
- Freemaker+poi realizes dynamic generation and parsing of Excel files
- Unified interface for reading and writing data files in xml/json/ini and ubjson formats
猜你喜欢
MySQL --- 數據庫的基本操作
Virtual lab basic experiment tutorial -7 Polarization (2)
MySQL -- basic concept of database
Yingguang single chip microcomputer development specification pmc131 with AD chip to detect battery voltage single chip microcomputer sop8/14
[target tracking] | data set summary
Use Zadig to build a continuous delivery platform from 0 to 1
[games101] operation 4 B é zier curve
【曆史上的今天】7 月 2 日:BitTorrent 問世;商業系統 Linspire 被收購;索尼部署 PlayStation Now
自定义一个loading指令
[golang | grpc] generate certificates using OpenSSL
随机推荐
PHP gets the number of days, hours, minutes and seconds between the two timestamps
Wasserstein slim gain with clipping penalty (wsgain-cp) introduction and code implementation -- missing data filling based on generating countermeasure network
Easyai notes - deep learning
【历史上的今天】7 月 2 日:BitTorrent 问世;商业系统 Linspire 被收购;索尼部署 PlayStation Now
Bluetooth technology | new working mode of wearable devices of the Internet of things, and Bluetooth ble helps the new working mode
一日2篇Nature!中科大校友段镶锋团队纳米材料新成果,曾是贝尔比奖章第三位华人得主...
Freemaker+poi realizes dynamic generation and parsing of Excel files
MySQL -- basic operation of database
Typescript
vimium映射鍵
Keras' deep learning practice -- gender classification based on vgg19 model
pytorch支持32位吗?
[golang | grpc] generate certificates using OpenSSL
567. Arrangement in string
把xshell连接服务器关掉,运行的jar包就自动停止的解决方案
MB10M-ASEMI整流桥MB10M
一个优秀程序员可抵五个普通程序员!
好评率计算
台风来袭,多景区暂时关闭,省文旅厅提醒注意安全!
Pfc232-sop8/14/16 should be wide-ranging and can be tape programmed with burning program