C#导入导出数据你该知道的方法。
导入数据

using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common { public static class Import { /// <summary> /// 获取导入的Excel的列名(第一行Titile) /// </summary> /// <returns></returns> public static List<string> GetFieldNames(string filePath) { ISheet sheet = GetSheet(filePath); List<string> filedNameList = new List<string>(); try { if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { filedNameList.Add(cellValue); } } } } } catch (Exception ex) { throw ex; } return filedNameList; } /// <summary> /// 将excel中的数据导入到DataTable中 /// </summary> /// <param name="sheetName">excel工作薄sheet的名称</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public static DataTable ExcelToDataTable(string filePath) { ISheet sheet = GetSheet(filePath); DataTable data = new DataTable(); int startRow = 0; try { if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; //最后一列的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //没有数据的行默认是null DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { throw ex; } } /// <summary> /// 获取sheet /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static ISheet GetSheet(string filePath) { ISheet sheet = null; MemoryStream memoryStream = CommonHelper.ReadFile(filePath); memoryStream.Position = 0; try { IWorkbook workbook = null; if (filePath.IndexOf(".xlsx") > 0) // 2007版本 { workbook = new XSSFWorkbook(memoryStream); } else if (filePath.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(memoryStream); memoryStream.Close(); memoryStream.Dispose(); sheet = workbook.GetSheetAt(0); return sheet; } catch (Exception ex) { memoryStream.Close(); memoryStream.Dispose(); throw ex; } } } }
导出数据

using CRM.Models.Base; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Common.Utils { public class Export { public static byte[] ExportToExcel<T>(List<T> modelList) { byte[] resultByte = null; IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象 ISheet sheet = workbook.CreateSheet(); //填充表头 IRow dataRow = sheet.CreateRow(0); System.Reflection.PropertyInfo[] ps = typeof(T).GetProperties(); for (int i = 0; i < ps.Count(); i++) { //object obj = ps[i].GetValue(typeof(T), null); string name = ps[i].Name; dataRow.CreateCell(i).SetCellValue(name); } //填充内容 for (int i = 0; i < modelList.Count; i++) { dataRow = sheet.CreateRow(i + 1); var type = modelList[i].GetType(); ps = type.GetProperties(); for (int j = 0; j < ps.Count(); j++) { object obj = ps[j].GetValue(modelList[i], null); if (obj != null) dataRow.CreateCell(j).SetCellValue(obj.ToString()); } } //保存 using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); resultByte = ms.ToArray(); ms.Dispose(); } return resultByte; } /// <summary> /// 根据DateTable导出Excel /// </summary> /// <param name="dt"></param> /// <returns></returns> public static byte[] ExportToExcel(DataTable dt) { byte[] resultByte = null; IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象 ISheet sheet = workbook.CreateSheet(); //填充表头 IRow dataRow = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { string name = dt.Columns[i].ColumnName; dataRow.CreateCell(i).SetCellValue(name); } //填充内容 for (int i = 0; i < dt.Rows.Count; i++) { dataRow = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { object obj = dt.Rows[i][j]; if (obj != null) { dataRow.CreateCell(j).SetCellValue(obj.ToString()); } } } //保存 using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); resultByte = ms.ToArray(); ms.Dispose(); } return resultByte; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?