1. 程式人生 > >datatable導出excel---NPOI

datatable導出excel---NPOI

pub for ring toe tac erro int head columns

//根據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;
}
}

}

datatable導出excel---NPOI