C# · 12月 19, 2021

C#利用NPOI导出Excel类(简单版)

代码:

using System.Data; System.IO; NPOI.HSSF.UserModel; NPOI.SS.UserModel;namespace ahwildlife.Utils{ /// <summary> /// Excel工具类 利用NPOI生成Excel </summary> public class ExcelUtil { #region 生成Excel <summary> 生成Excel </summary> static void CreateExcel(DataTable dt,string path) { HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet(“Sheet1”) : workbook.CreateSheet(dt.TableName);//创建工作表 #region 标题 IRow row = sheet.CreateRow(0);在工作表中添加一行 for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i);在行中添加一列 cell.SetCellValue(dt.Columns[i].ColumnName);设置列的内容 } #endregion #region 填充数据 1; i <= dt.Rows.Count; i++)遍历DataTable行 { DaTarow daTarow = dt.Rows[i – 1]; row = sheet.CreateRow(i);在工作表中添加一行 int j = 0; j < dt.Columns.Count; j++)遍历DataTable列 { ICell cell = row.CreateCell(j);在行中添加一列 cell.SetCellValue(daTarow[j].ToString()); } } #region 输出到Excel MemoryStream ms = MemoryStream(); workbook.Write(ms); using (FileStream fs = FileStream(path,FileMode.Create,FileAccess.Write)) { byte[] bArr = ms.ToArray(); fs.Write(bArr,0,bArr.Length); fs.Flush(); } #endregion } }}View Code