1、下载/导包
http://npoi.codeplex.com/releases
下载:NPOI binary 2.1.3.1
解压源码包后的文件目录结构
************************************
+ dotnet2
+ dotnet4
+ logo
- LICENSE
- Read Me.txt
- Release Notes.txt
************************************
进入 dotnet2 || dotnet4
2、添加四个.dll引用
NPOI.dll
NPOI.OOXML.dll
NPOI.OpenXml4Net.dll
NPOI.OpenmlFormats.dll
3、在官方文档拿示例
https://dotblogs.com.tw/killysss/archive/2010/01/27/13344.aspx
4、生成方法
public ResultSet<T> ExportDataSetToExcel<T>(List<T> list, string downloadPath, string destFilename, string searchParams = "") { //创建excel 工作簿对象 IWorkbook workbook = CreateWorkbook(downloadPath + destFilename); //创建excel 表对象 ISheet sheet = CreateSheet<T>(list, searchParams, workbook); //写入到excel文件中 var stream = WorkBookToMemoryStream(workbook); WriteSteamToFile(stream, downloadPath + destFilename); return new ResultSet<T> { IsSuccess = true }; }
private IWorkbook CreateWorkbook(string templateFileName) { using (FileStream file = new FileStream(templateFileName, FileMode.Open, FileAccess.Read)) { IWorkbook workbook; if ((templateFileName.Substring(templateFileName.LastIndexOf(".")).IndexOf("xlsx")) > 0) { workbook = new XSSFWorkbook(file); } else { workbook = new HSSFWorkbook(file); } return workbook; } }
private static ISheet CreateSheet<T>(List<T> list, string searchParams, IWorkbook workbook) { ISheet sheet = workbook.GetSheet("Sheet1"); var bgRow = sheet.FirstRowNum; var edRow = sheet.LastRowNum; //插入查询条件到excel sheet.GetRow(2).GetCell(1).SetCellValue(searchParams); IRow rData = sheet.GetRow(bgRow);//excel表的第一行内容 DataSet listDataSet = list.ToDataSet<T>(); for (int i = 0; i < listDataSet.Tables[0].Rows.Count; i++) { var row = listDataSet.Tables[0].Rows[i]; IRow irow = sheet.CreateRow(edRow + 1); for (int j = rData.FirstCellNum; j < rData.LastCellNum; j++) { var columnDataSet = row[rData.GetCell(j).ToString()].IfNull(0); var cell = irow.CreateCell(j); cell.SetCellValue(columnDataSet.ToString()); } edRow++; } //删除excel一第行 sheet.ShiftRows(1, edRow, -1); return sheet; }
/// <summary> /// 转换成输出流 /// </summary> /// <param name="InputStream"></param> /// <returns></returns> public static MemoryStream WorkBookToMemoryStream(IWorkbook workbook) { MemoryStream file = new MemoryStream(); workbook.Write(file); return file; }
/// <summary> /// 写入到excel文件中 /// </summary> /// <param name="ms"></param> /// <param name="FileName"></param> private static void WriteSteamToFile(MemoryStream ms, string FileName) { FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write); byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); data = null; ms = null; fs = null; }
初步搞定,能根据传来的excel模板插入数据生成一个新的excel