NET npoi 保存文件

匿名 (未验证) 提交于 2019-12-02 22:06:11

npoi完整代码:NET npoi帮助类

        public static void DataTableToExcel(List<DataTable> dataTables, string filePath)         {             if (dataTables == null || !dataTables.Any())                 throw new Exception("dataTables不能为null");             bool isOldThan2007 = Path.GetExtension(filePath)?.ToLower() == ".xls";             IWorkbook book = dataTables.ToWorkbook(isOldThan2007);             using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))             {                 book.Write(fs);             }         }

        public static IWorkbook ToWorkbook(this List<DataTable> dataTables, bool isOldThan2007)         {             IWorkbook book = isOldThan2007 ? new HSSFWorkbook() : (IWorkbook)new XSSFWorkbook();             foreach (var dataTable in dataTables)             {                 if (dataTable == null)                     continue;                 ISheet sheet = book.CreateSheet(dataTable.TableName);                 IRow headerRow = sheet.CreateRow(0);                 foreach (DataColumn column in dataTable.Columns)                 {                     headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);                 }                  for (int i = 0; i < dataTable.Rows.Count; i++)                 {                     DataRow row = dataTable.Rows[i];                     IRow dataRow = sheet.CreateRow(i + 1);                     for (int j = 0; j < dataTable.Columns.Count; j++)                     {                         dataRow.CreateCell(j).SetCellValue(row[j]?.ToString());                     }                 }             }             return book;         }

文章来源: NET npoi 保存文件
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!