当前位置:网站首页>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
边栏推荐
- 铁塔安全监测系统 无人值守倾角振动监测系统
- Pfc232-sop8/14/16 should be wide-ranging and can be tape programmed with burning program
- Laravel框架安装时遇到的坑
- NVIDIA graphics card failed to initialize nvml driver/library version mismatch error solution
- WPS inserts a picture and displays it completely
- Pms150c Yingguang MCU development case
- Editor Editor Extension add button and logo in scene view
- Use Zadig to build a continuous delivery platform from 0 to 1
- Android cycle timer implementation, to achieve fixed Android cache cleaning
- Yingguang MCU development case
猜你喜欢

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

微信小程序视频分享平台系统毕业设计毕设(2)小程序功能

Easyai notes - machine learning

微信核酸检测预约小程序系统毕业设计毕设(1)开发概要

微信小程序视频分享平台系统毕业设计毕设(4)开题报告

开发一个禁止删除namespace的控制器

Embedded ~ introduction

微信核酸检测预约小程序系统毕业设计毕设(5)任务书

Detailed explanation of map set

Wechat nucleic acid detection and appointment applet system graduation design (3) background function
随机推荐
Tips for self defined packaging of Yingguang SCM 003 burner
MySQL安装与配置
D构造函数问题
Explain kubernetes network model in detail
qt的内存映射
No such file or directory: ‘/tmp/tmpxxx/tmpxxx. py‘
Architecture design - ID generator "suggestions collection"
自定义一个loading指令
D constructor problem
Development and application case of pms134 scheme of Yingguang single chip microcomputer with original packaging
辉芒微IO单片机FT60F11F-MRB
微信小程序视频分享平台系统毕业设计毕设(3)后台功能
Intelligent hydropower meter energy consumption monitoring cloud platform
【Zuul】com. netflix. zuul. exception. ZuulException: Hystrix Readed time out
WPS inserts a picture and displays it completely
Detailed explanation of map set
MySQL -- basic operation of database
Mysql - opérations de base de la base de données
好玩的免费GM游戏整理汇总
Aptos教程-参与官方激励测试网(AIT2 激励测试网)