传入dattatable:
public void DataTableToExcel(DataTable dt, string filepath, string sheetname)
{
IWorkbook excel = new HSSFWorkbook();//创建.xls文件
ISheet sheet = excel.CreateSheet("sheet1"); //创建sheet
DataTable datatable = dt;//获取数据源datatable
IRow row = sheet.CreateRow(0);//创建行对象,填充表头
// foreach (DataColumn column in datatable.Columns)
// {
// row.CreateCell(0).SetCellValue("编号");
// row.CreateCell(1).SetCellValue("名称");
// row.CreateCell(2).SetCellValue("方式");
// }
foreach (DataColumn column in datatable.Columns)
{
row.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
//填充内容()
for (int i = 0; i < datatable.Rows.Count; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < datatable.Columns.Count; j++)
{
row.CreateCell(j).SetCellValue(datatable.Rows[i][j].ToString());
sheet.AutoSizeColumn(j);
}
}
//写入文件
string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
FileStream xlsfile = new FileStream(DesktopPath + @"\"+sheetname + DateTime.Now.ToString("yyyyMMdd") + ".xls", FileMode.Create);
excel.Write(xlsfile);
xlsfile.Close();
MessageBox.Show("Excel文件已导出到桌面", "提示");
}