美文网首页
NPIO导出excel

NPIO导出excel

作者: 你我知道的事 | 来源:发表于2017-08-01 16:47 被阅读0次

    1、首先需要添加引用:NPOI.dll文件

    2、using NPOI.SS.UserModel;

         using NPOI.HSSF.UserModel;

         using System.IO;

         using System.Collections;

    3、导出excel文件:

    private bool exportExcel(string excename,DataTable dataTable)

    {

    bool result = false;

    DataTable dt = new DataTable();

    IWorkbook wb = null;

    ICell cell = null;

    ISheet sheet = null;

    FileStream stm = null;

    try

    {

    dt = dataTable;

    wb = new HSSFWorkbook();

    //创建表

    sheet = wb.CreateSheet("Sheet0");

    int rowCount = dt.Rows.Count;

    int columnCount = dt.Columns.Count;

    IRow row = sheet.CreateRow(0);

    //设置列头

    for (int c = 0; c < columnCount; c++)

    {

    cell = row.CreateCell(c);

    cell.SetCellValue(dt.Columns[c].ColumnName);

    }

    //设置每行每列的单元格

    for (int i = 0; i < rowCount; i++)

    {

    row = sheet.CreateRow(i + 1);

    for (int j = 0; j < columnCount; j++)

    {

    cell = row.CreateCell(j);//excel第二行开始写入数据

    cell.SetCellValue(dt.Rows[i][j].ToString());

    }

    }

    try

    {

    using (stm = File.OpenWrite(excename + ".xls"))

    {

    wb.Write(stm);

    result = true;

    MessageBox.Show("提示:文件导出成功!");

    }

    }

    catch (IOException ex)

    {

    MessageBox.Show(ex.Message);

    }

    return result;

    }

    catch (Exception ex)

    {

    if (stm != null)

    {

    stm.Close();

    }

    return false;

    }

    }

    相关文章

      网友评论

          本文标题:NPIO导出excel

          本文链接:https://www.haomeiwen.com/subject/jznjlxtx.html