NPIO导出excel

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;

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容