1、首先需要添加引用:NPOI.dll文件
2伟骨、using NPOI.SS.UserModel;
? ? ?using NPOI.HSSF.UserModel;
? ? ?using System.IO;
? ? ?using System.Collections;
3、導(dǎo)出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();
//創(chuàng)建表
sheet = wb.CreateSheet("Sheet0");
int rowCount = dt.Rows.Count;
int columnCount = dt.Columns.Count;
IRow row = sheet.CreateRow(0);
//設(shè)置列頭
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
}
//設(shè)置每行每列的單元格
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行開(kāi)始寫(xiě)入數(shù)據(jù)
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
try
{
using (stm = File.OpenWrite(excename + ".xls"))
{
wb.Write(stm);
result = true;
MessageBox.Show("提示:文件導(dǎo)出成功!");
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
catch (Exception ex)
{
if (stm != null)
{
stm.Close();
}
return false;
}
}