NPOI 将DataSet保存成Excel文件
NPOI 简介(来自百度)
NPOI是指构建在POI 3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目。
需要通过 NuGet 安装 NPOI 插件。

主要代码实现:
using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.Data; namespace StudentVocabularyInfo { /// <summary> /// DataSet转Excel帮助类。 /// </summary> internal class DataSetToExcel { /// <summary> /// DataSet转Excel方法。 /// </summary> /// <param name="ds">数据集。</param> /// <param name="path">文件保存地址。</param> /// <param name="addColumn">是否将列作为第一列数据。</param> /// <returns></returns> /// <exception cref="System.Exception"></exception> public static bool DataSetToExcelXSSF(DataSet ds, string path, bool addColumn = true) { try { XSSFWorkbook hw = new XSSFWorkbook(); for (int t = 0; t < ds.Tables.Count; t++) { ISheet sheet2 = (ISheet)hw.CreateSheet(ds.Tables[t].TableName); // 将列名插入到第一行数据。 if(addColumn) { IRow rowCol2 = (IRow)sheet2.CreateRow(0); for (int j = 0; j < ds.Tables[t].Columns.Count; j++) { ICell cell = (ICell)rowCol2.CreateCell(j); cell.SetCellValue(ds.Tables[t].Columns[j].ColumnName); } } for (int i = 0; i < ds.Tables[t].Rows.Count; i++) { IRow row = null; if (addColumn) { row = (IRow)sheet2.CreateRow(i + 1); } else { row = (IRow)sheet2.CreateRow(i); } for (int j = 0; j < ds.Tables[t].Columns.Count; j++) { ICell cell = row.CreateCell(j); // 获取列类型。 var columnType = ds.Tables[t].Columns[j].DataType; // 如果列是整型数据,需要进行转换,这里需要列已经设置过属性,如果没有需要通过列数进行判断,比如第一列:j==0。 if (columnType == typeof(int)) { int num = -1; bool flag = int.TryParse(ds.Tables[t].Rows[i][j].ToString(), out num); if (flag) { cell.SetCellValue(num); } else { cell.SetCellValue(ds.Tables[t].Rows[i][j].ToString()); } } else { if (ds.Tables[t].Rows[i][j].ToString().Contains("<br>")) { ICellStyle cs = hw.CreateCellStyle(); cs.WrapText = true; cell.CellStyle = cs; } cell.SetCellValue(ds.Tables[t].Rows[i][j].ToString().Replace("<br>", "\r\n")); } } } } FileStream file = new FileStream(path, FileMode.Create); hw.Write(file); file.Close(); if (!File.Exists(path)) { return false; } return true; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } } }
调用:
DataSetToExcel.DataSetToExcelXSSF(ds, filePath);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构