码迷,mamicode.com
首页 > 其他好文 > 详细

datatable导出excel---NPOI

时间:2018-03-14 12:42:34      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:reac   exce   work   exp   文件   name   添加   port   set   

//根据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

标签:reac   exce   work   exp   文件   name   添加   port   set   

原文地址:https://www.cnblogs.com/jathon/p/8566377.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!