当前位置:网站首页>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
边栏推荐
- Customize a loading instruction
- Redisson high performance redis distributed lock source code analysis
- Microsoft LDAP 配置页中输入有效的用户名及密码,microsoft ldap 配置页中输入有效的用户名
- 微信小程序视频分享平台系统毕业设计毕设(4)开题报告
- 微信小程序视频分享平台系统毕业设计毕设(1)开发概要
- Modbus protocol communication exception
- vimium映射键
- 515. Find the maximum value in each tree row
- 架构设计——ID生成器「建议收藏」
- Three methods of MySQL backup
猜你喜欢

Explain kubernetes network model in detail

Microsoft LDAP 配置页中输入有效的用户名及密码,microsoft ldap 配置页中输入有效的用户名

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

aloam 代码阅读与总结

MySQL installation and configuration

微信小程序视频分享平台系统毕业设计毕设(1)开发概要

NVIDIA graphics card failed to initialize nvml driver/library version mismatch error solution

Babbitt | metauniverse daily must read: can you buy a virtual anchor for 1000 yuan? Is this the live gospel of small businesses or "cutting leeks"

Nvidia 显卡 Failed to initialize NVML Driver/library version mismatch 错误解决方案

能解决 80% 故障的排查思路
随机推荐
Simple understanding of cardinality sorting
Huimang micro IO MCU ft60f11f-mrb
Pfc232-sop8/14/16 should be wide-ranging and can be tape programmed with burning program
win10 kms activator
From a professional background, I can't get into a small company for interview
铁塔安全监测系统 无人值守倾角振动监测系统
515. Find the maximum value in each tree row
Easyai notes - machine learning
Pms150c Yingguang MCU development case
Calculation of favorable comment rate
Clé de cartographie vimium
Aloam code reading and summary
Enter a valid user name and password in the Microsoft LDAP configuration page, and enter a valid user name in the Microsoft LDAP configuration page
[golang | grpc] generate certificates using OpenSSL
Graduation summary
Problems needing attention in the development and debugging of Yingguang single chip microcomputer
Freemaker+poi realizes dynamic generation and parsing of Excel files
Does pytorch support 32 bits?
微信小程序视频分享平台系统毕业设计毕设(6)开题答辩PPT
Songhan sn8p2511 sop8 single chip microcomputer can be used for burning, providing single chip microcomputer scheme development and single chip microcomputer decryption