NPOI介绍:
NPOI优势:
下面使用到NPOI.HSSF进行实战(Microsoft Excel BIFF(Excel 97-2003)格式读写库)
第一步首先是要引入NPOI依赖包了
第二步,准备Excel模板
第三步编写代码
以下仅展示核心代码
public void PrintExcle(HttpQueryData httpQueryData, List<PrintData> prints) {
string path= "Excel模板.xls";//模板路径
Random random = new Random();
var localTemplatPath = TempFileAccess.TempDir + @"\" + httpQueryData.TaskNo + " " + prints[0].DeptName + random.Next(100000, 999999) + "Excel模板.xls";//新生成文件路径以及文件名与格式
File.Copy(path , localTemplatPath);
using (var fs = File.OpenRead(localTemplatPath))
{
//此处应该再判断文件的格式是xls还是xlsx,如果是xlsx则使用XSSFWorkbook
//HSSFWorkbook:是操作Excel2003以前(包括2003)的版本、XSSFWorkbook:是操作Excel2007的版本
var workbook = new HSSFWorkbook(fs);
var sheet = workbook.GetSheetAt(0);
//基本信息(Row和Cell分别代表着行、列,计数都是从0开始,比如说Excel里面第一个格子就是0,0)
//此处代码是根据自己的模板去写GetRow与GetCell的值
var rowIndex = 1;
sheet.GetRow(rowIndex).GetCell(1).SetCellValue(httpQueryData.TaskNo);
if(!string.IsNullOrWhiteSpace(httpQueryData.InputDate))
sheet.GetRow(rowIndex).GetCell(4).SetCellValue(httpQueryData.InputDate.Split(' ')[0]);
sheet.GetRow(rowIndex).GetCell(7).SetCellValue(DateTime.Now.ToString("yyyy-MM-dd"));
rowIndex = 2;
sheet.GetRow(rowIndex).GetCell(1).SetCellValue(httpQueryData.DelegateOrgName);
sheet.GetRow(rowIndex).GetCell(4).SetCellValue(" ");
sheet.GetRow(rowIndex).GetCell(7).SetCellValue(httpQueryData.BusinessFromDisplay);
rowIndex = 3;
sheet.GetRow(rowIndex).GetCell(1).SetCellValue(" ");
sheet.GetRow(rowIndex).GetCell(4).SetCellValue(" ");
sheet.GetRow(rowIndex).GetCell(7).SetCellValue(prints[0].DeptName);
//****动态列表信息,先加行,在填入信息
if (prints.Count > 0)
{
for (int i = 0; i < prints.Count - 1; i++)
{
sheet.CopyRow(5, 6 + i);
}
}
int count = 0;
rowIndex = 5;
for (int i = 0; i < prints.Count; i++) {
var curRow = sheet.GetRow(rowIndex);
var data = prints[i];
curRow.GetCell(0).SetCellValue(i+1);
curRow.GetCell(1).SetCellValue(data.Name);
curRow.GetCell(3).SetCellValue(data.FactoryNo);
curRow.GetCell(4).SetCellValue(data.Count);
curRow.GetCell(5).SetCellValue(data.InspectionAttribute);
curRow.GetCell(7).SetCellValue(data.CertificateRequirements);
curRow.GetCell(9).SetCellValue(data.Remark);
count = count + int.Parse(data.Count);
rowIndex = rowIndex + 1;
}
sheet.GetRow(rowIndex).GetCell(4).SetCellValue(count);
//保存
using (FileStream localFs = File.OpenWrite(localTemplatPath))
{
workbook.Write(localFs);
localFs.Close();
}
}
System.Diagnostics.Process.Start(localTemplatPath);
}
最终效果