当前位置:网站首页>Export Excel files using npoi
Export Excel files using npoi
2022-07-02 18:11:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
Use NPOI export Excel file , This example uses ASP.NET MVC.
1、 Use NPOI export Excel file
example : Export product list .
requirement :1、 adopt NPOI Export product list information ;
2、 Use Excel Function to calculate the total amount of goods ;
stay Controllers Created in the controller directory ExportController.cs controller
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>
/// Export product list
/// </summary>
public FileResult ExportProduct()
{
// Create a new xls file
HSSFWorkbook workbook = new HSSFWorkbook();
// establish DocumentSummaryInformation( optional )
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = " Shenzhen e-commerce Co., Ltd ";
dsi.Category = " report form ";
// establish SummaryInformation( optional )
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = " List of goods ";
si.Title = " Product list Export ";
si.Author = "Kevin Pan";
// Assign the created object to Workbook
workbook.DocumentSummaryInformation = dsi;
workbook.SummaryInformation = si;
// Create a Sheet
ISheet sheet = workbook.CreateSheet("Sheet1");
sheet.DefaultRowHeight = 300;
// Create title
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 = " Song style ";
fontTitle.FontHeightInPoints = 18;
styleTitle.SetFont(fontTitle);
ICell cellTitle = rowTitle.CreateCell(0);
cellTitle.SetCellValue(" List of goods ");
cellTitle.CellStyle = styleTitle;
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 5)); // merge cell
// Create a table style
IFont font = workbook.CreateFont();
font.FontName = " Song style ";
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);
// Create header
IRow rowHead = sheet.CreateRow(1);
rowHead.CreateCell(0).SetCellValue(" Serial number ");
rowHead.GetCell(0).CellStyle = style;
sheet.SetColumnWidth(0, 256 * 5);
rowHead.CreateCell(1).SetCellValue(" Name of commodity ");
rowHead.GetCell(1).CellStyle = style;
sheet.SetColumnWidth(1, 256 * 25);
rowHead.CreateCell(2).SetCellValue(" Brand of goods ");
rowHead.GetCell(2).CellStyle = style;
sheet.SetColumnWidth(2, 256 * 20);
rowHead.CreateCell(3).SetCellValue(" commodity price ");
rowHead.GetCell(3).CellStyle = style;
sheet.SetColumnWidth(3, 256 * 15);
rowHead.CreateCell(4).SetCellValue(" Number ");
rowHead.GetCell(4).CellStyle = style;
sheet.SetColumnWidth(3, 256 * 10);
rowHead.CreateCell(5).SetCellValue(" Total sum ");
rowHead.GetCell(5).CellStyle = style;
sheet.SetColumnWidth(3, 256 * 15);
// Get product list data
List<ProductModel> dataList = GetProductList();
// Bind table contents
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;
// Set function , Calculate the total amount
rowContent.CreateCell(5).SetCellFormula(String.Format("$D{0}*$E{0}", rowindex+1));
rowContent.GetCell(5).CellStyle = style;
rowindex++;
xh++;
}
// Output
System.IO.MemoryStream ms = new System.IO.MemoryStream();
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", " List of goods .xls");
}2、 be based on .xls Template export Excel file
example : be based on .xls Template export order information ( Pictured 1)
requirement :1、 Using a .xls Template export order information ;
2、 Use Excel Function to calculate the total amount of orders and goods ;
chart 1 be based on .xls Template export order information
/// <summary>
/// Export order information
/// </summary>
public FileResult ExportOrder()
{
// Get order information
OrderModel order = GetOrderInfo();
// obtain Excel Templates
string fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/Template/order.xls";
FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
// Create a xls file
HSSFWorkbook workbook = new HSSFWorkbook(file);
// obtain Sheet
ISheet sheet = workbook.GetSheet("Sheet1");
// Export order information
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)"); // Set function , Calculate the total order amount
sheet.GetRow(2).CreateCell(1).SetCellValue(order.CustomName);
sheet.GetRow(2).CreateCell(3).SetCellValue(order.CustomAddress);
// Export product list
if (order.ProductList != null && order.ProductList.Count > 0)
{
// Create header
IRow rowHead = sheet.CreateRow(4);
rowHead.CreateCell(0).SetCellValue(" Serial number ");
sheet.SetColumnWidth(0, 256 * 15);
rowHead.CreateCell(1).SetCellValue(" Name of commodity ");
sheet.SetColumnWidth(1, 256 * 25);
rowHead.CreateCell(2).SetCellValue(" Brand of goods ");
sheet.SetColumnWidth(2, 256 * 20);
rowHead.CreateCell(3).SetCellValue(" commodity price ");
sheet.SetColumnWidth(3, 256 * 15);
rowHead.CreateCell(4).SetCellValue(" Number ");
sheet.SetColumnWidth(3, 256 * 10);
rowHead.CreateCell(5).SetCellValue(" Total sum ");
sheet.SetColumnWidth(3, 256 * 15);
// Bind table contents
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)); // Set function , Calculate the total amount
rowindex++;
xh++;
}
}
// Output
System.IO.MemoryStream ms = new System.IO.MemoryStream();
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", " Order information .xls");
}3、 Other code
3.1 Entity class
stay Models Create in the model directory ProductModel.cs and OrderModel.cs Entity class
/// <summary>
/// Commodity information entity class
/// </summary>
public class ProductModel
{
/// <summary>
/// Name of commodity
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// Brand of goods
/// </summary>
public string ProductBrand { get; set; }
/// <summary>
/// commodity price
/// </summary>
public decimal ProductPrice { get; set; }
/// <summary>
/// Number
/// </summary>
public int Quantity { get; set; }
}/// <summary>
/// Order information entity class
/// </summary>
public class OrderModel
{
/// <summary>
/// The order no.
/// </summary>
public string OrderNo { get; set; }
/// <summary>
/// Order time
/// </summary>
public DateTime OrderTime { get; set; }
/// <summary>
/// Total sum
/// </summary>
public decimal Amount { get; set; }
/// <summary>
/// Customer name
/// </summary>
public string CustomName { get; set; }
/// <summary>
/// Customer address
/// </summary>
public string CustomAddress { get; set; }
/// <summary>
/// List of goods
/// </summary>
public List<ProductModel> ProductList { get; set; }
}3.2 Get product and order data
/// <summary>
/// Get a list of products
/// </summary>
public List<ProductModel> GetProductList()
{
List<ProductModel> productList = new List<ProductModel>();
ProductModel product1 = new ProductModel(){
ProductName = " Apple IPhone6 mobile phone ",
ProductBrand = " Apple ",
ProductPrice = 4999,
Quantity = 4
};
ProductModel product2 = new ProductModel()
{
ProductName = " Samsung smartphones ",
ProductBrand = " samsung ",
ProductPrice = 3800,
Quantity = 3
};
ProductModel product3 = new ProductModel()
{
ProductName = " Panasonic LCD TV ",
ProductBrand = " panasonic ",
ProductPrice = 3800,
Quantity = 2
};
productList.Add(product1);
productList.Add(product2);
productList.Add(product3);
return productList;
}
/// <summary>
/// Get order information
/// </summary>
public OrderModel GetOrderInfo()
{
OrderModel order = new OrderModel() {
OrderNo = "P20140929001",
OrderTime = DateTime.Now,
CustomName = " Zhang San ",
CustomAddress = " Luohu District, Shenzhen City, Guangdong Province ",
ProductList = GetProductList()
};
return order;
}3.3 View
stay Views Create in the view directory Index.cshtml
<h2> Use NPOI Generate Excel file </h2>
<a href="@Url.Action("ExportProduct","Export")"> Export goods </a>
<a href="@Url.Action("ExportOrder","Export")"> Export order </a>Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/148244.html Link to the original text :https://javaforall.cn
边栏推荐
- PHP gets the number of days, hours, minutes and seconds between the two timestamps
- Ora-19838 -- restore control files to the standby database
- What should we pay attention to in the development process of Yingguang single chip microcomputer?
- MySQL安装与配置
- 把xshell连接服务器关掉,运行的jar包就自动停止的解决方案
- 把xshell連接服務器關掉,運行的jar包就自動停止的解决方案
- 如何下载微信支付证书(API证书)
- Editor编辑器扩展在Scene View添加按钮和logo
- 自定义一个loading指令
- Yingguang single chip microcomputer (MCU popular science)
猜你喜欢

如何开启IDEA的Run Dashboard功能

Viewing technological changes through Huawei Corps (VI): smart highway

Linux中,mysql设置job任务自动启动

Asemi rectifier bridge umb10f parameters, umb10f specifications, umb10f package

详解Kubernetes网络模型

MySQL advanced - transaction and index

Customize a loading instruction

MySQL安装与配置

巴比特 | 元宇宙每日必读:一千块就能买一个虚拟主播?这是小企业的直播福音还是在“割韭菜”?...

Nvidia 显卡 Failed to initialize NVML Driver/library version mismatch 错误解决方案
随机推荐
应广单片机开发调试应注意的问题
Embedded ~ introduction
Outsourcing for five years, abandoned
[games101] operation 4 B é zier curve
详解Kubernetes网络模型
977.有序数组的平方
A4988与42步进电机
In Linux, MySQL sets the job task to start automatically
Simple understanding of cardinality sorting
Picking up the camera is the best artistic healing
应广单片机003烧录器自定义封装使用技巧
Troubleshooting ideas that can solve 80% of faults
Ora-19838 -- restore control files to the standby database
Development and application case of pms134 scheme of Yingguang single chip microcomputer with original packaging
Yingguang single chip microcomputer development specification pmc131 with AD chip to detect battery voltage single chip microcomputer sop8/14
Modbus protocol communication exception
Editor编辑器扩展在Scene View添加按钮和logo
辉芒微IO单片机FT60F11F-MRB
基数排序的简单理解
Laravel框架安装时遇到的坑