当前位置:网站首页>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
边栏推荐
- 应广单片机开发案例
- From a professional background, I can't get into a small company for interview
- 好评率计算
- 求求你们,别再刷 Star 了!这跟“爱国”没关系!
- 977. Square of ordered array
- wait_ for_ Gap -- restore archive from primary archive to secondary Archive
- Redisson high performance redis distributed lock source code analysis
- Yingguang single chip microcomputer pms150/pmc150/pms150c consumer single chip microcomputer
- 应广单片机003烧录器自定义封装使用技巧
- 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
猜你喜欢
ORA-19838 -- 恢复控制文件到备库
Pychar modify pep8 e501 line too long > 0 characters
微信小程序视频分享平台系统毕业设计毕设(1)开发概要
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
微信小程序视频分享平台系统毕业设计毕设(6)开题答辩PPT
MySQL安装与配置
aloam 代码阅读与总结
开发一个禁止删除namespace的控制器
如何下载微信支付证书(API证书)
深入理解ThreadLocal
随机推荐
辉芒微IO单片机FT60F11F-MRB
Pms132b single chip microcomputer TWS digital tube Bluetooth charging chamber program development
详解Kubernetes网络模型
把xshell連接服務器關掉,運行的jar包就自動停止的解决方案
1288_ Implementation analysis of vtask resume() interface and interrupt Security version interface in FreeRTOS
人人工势场法
No such file or directory: ‘/tmp/tmpxxx/tmpxxx. py‘
Mysql 备份的三种方式
Easyai notes - deep learning
Vi/vim delete: one line, one character, word, the first character of each line command
MySQL --- 数据库的基本概念
Solution pour arrêter automatiquement les paquets Jar en cours d'exécution en éteignant le serveur de connexion xshell
ORA-19838 -- 恢复控制文件到备库
如何开启IDEA的Run Dashboard功能
WPS inserts a picture and displays it completely
Huimang micro IO MCU ft60f011a-rb
Three methods of MySQL backup
Viewing technological changes through Huawei Corps (VI): smart highway
Wasserstein Slim GAIN with Clipping Penalty(WSGAIN-CP)介绍及代码实现——基于生成对抗网络的缺失数据填补
wait_ for_ Gap -- restore archive from primary archive to secondary Archive