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;

}

}

你可能感兴趣的:(NPIO导出excel)