将DataTable中的数据导出到Excel

时间:2024-11-12 11:04:44
 public static void Export(System.Data.DataTable dt,NPOI.HSSF.UserModel.HSSFWorkbook workbook,string FilePath)
{
if(dt.Rows.Count == )
{
System.Windows.MessageBox.Show("尚未读取到任何数据");
return;
}
ISheet sheet = workbook.CreateSheet("导出数据");
HSSFCellStyle styleHeader =(HSSFCellStyle)workbook.CreateCellStyle();
styleHeader.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeight = * ;
font.Color = HSSFColor.Red.Index;
styleHeader.SetFont(font);
HSSFCellStyle style = (HSSFCellStyle)workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
using(FileStream fs = new FileStream(FilePath + "\\导出数据.xls",FileMode.Create))
{
IRow rowHeader = sheet.CreateRow();
for (int col = ; col < dt.Columns.Count; col++)
{
ICell cellHeader = rowHeader.CreateCell(col);
cellHeader.SetCellValue(dt.Columns[col].ColumnName);
sheet.SetColumnWidth(col, * );
cellHeader.CellStyle = styleHeader;
}
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i);
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i - ][j].ToString());
cell.CellStyle = style;
}
}
workbook.Write(fs);
System.Windows.MessageBox.Show("保存成功");
}
}