当前位置:网站首页>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
边栏推荐
猜你喜欢
Redisson high performance redis distributed lock source code analysis
一个优秀程序员可抵五个普通程序员!
微信小程序视频分享平台系统毕业设计毕设(6)开题答辩PPT
开发一个禁止删除namespace的控制器
Aloam code reading and summary
Two pieces of nature a day! Duan Fengfeng, an alumnus of the University of science and technology of China, was the third Chinese winner of the belby medal
MySQL --- 数据库的基本概念
微信小程序视频分享平台系统毕业设计毕设(2)小程序功能
MySQL --- 數據庫的基本操作
1288_ Implementation analysis of vtask resume() interface and interrupt Security version interface in FreeRTOS
随机推荐
Nvidia 显卡 Failed to initialize NVML Driver/library version mismatch 错误解决方案
Yingguang single chip microcomputer (MCU popular science)
Easyai notes - deep learning
In Linux, MySQL sets the job task to start automatically
pycharm 修改 pep8 E501 line too long > 0 characters
Detailed explanation of map set
毕业总结
读写 XML/JSON/INI 和 UBJSON 等格式的数据文件的统一接口
vi/vim 删除:一行, 一个字符, 单词, 每行第一个字符 命令
qt的内存映射
MySQL -- basic operation of database
Viewing technological changes through Huawei Corps (VI): smart highway
Huimang micro IO MCU ft60f011a-rb
如何下载微信支付证书(API证书)
Microsoft LDAP 配置页中输入有效的用户名及密码,microsoft ldap 配置页中输入有效的用户名
Three methods of MySQL backup
977. Square of ordered array
Does pytorch support 32 bits?
vimium映射鍵
Explain kubernetes network model in detail