NET npoi 保存文件

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();
foreach (DataColumn column in dataTable.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
} for (int i = ; i < dataTable.Rows.Count; i++)
{
DataRow row = dataTable.Rows[i];
IRow dataRow = sheet.CreateRow(i + );
for (int j = ; j < dataTable.Columns.Count; j++)
{
dataRow.CreateCell(j).SetCellValue(row[j]?.ToString());
}
}
}
return book;
}
上一篇:Android -- 使用主题配置文件,去掉程序启动界面的短暂黑屏


下一篇:iOS_单例