//根据datatable导出excel demo,npoi的使用
//首先添加引用文件.net4.0文件夹下dll
public static void ExportToExcel(DataTable table, string path,string[] list)//list为自定义的列标题,函数直接调用即可
{
MemoryStream ms = new MemoryStream();
using (table)
{
IWorkbook workbook = new HSSFWorkbook();//由工作簿到工作表,由表到列
{
ISheet sheet = workbook.CreateSheet();
{
IRow headerRow = sheet.CreateRow(0);//自定义列名
for (int i = 0; i < list.Length; i++)
{
headerRow.CreateCell(i).SetCellValue(list[i]);
}
//foreach (DataColumn column in dt.Columns)//注释掉的语句作用为取数据库中列
//headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);如果标题没有设置,返回ColumnName的值
int rowIndex = 1;
foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
rowIndex++;
}
workbook.Write(ms);//将workbook写入到内存流
ms.Flush();
ms.Position = 0;
}
}
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);//将内存流中数据写到文件流
fs.Flush();
data = null;
}
}
}