NPOI操作excel之写入数据到excel表

时间:2021-01-20 20:41:14

在上一篇《NPOI操作excel之读取excel数据》我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中。

using System;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel; namespace NPOIOprateExcel
{
public class ExcelUtility
{
public static bool DataTableToExcel(DataTable dt)
{
bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
ISheet sheet = null;
ICell cell = null;
try
{
if (dt != null && dt.Rows.Count > )
{

              //大批量数据导出的时候,需要注意这样的一个问题,Excel2003格式一个sheet只支持65536行,excel 2007 就比较多,是1048576

              //需要ICSharpCode.SharpZipLib.dll库
              //workbook = new HSSFWorkbook(fs);//2003版本.xls
              workbook = new XSSFWorkbook(fs);// 2007版本.xlsx(保存的数据库大)

                    sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数 //设置列头
row = sheet.CreateRow();//excel第一行设为列头
for (int c = ; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
} //设置每行每列的单元格,
for (int i = ; i <rowCount; i++)
{
row = sheet.CreateRow(i+);
for (int j = ; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行开始写入数据
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
using (fs = File.OpenWrite(@"D:/myxls.xls"))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
result = true;
}
}
return result;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return false;
}
}
}
}

结果如下:

NPOI操作excel之写入数据到excel表