/// <summary>
/// DataTable数据导出为Excel
/// </summary>
/// <param name="dt">source</param>
/// <param name="workbook">new HSSFWorkbook()</param>
/// <param name="FilePath">存放路径</param>
public static void DataTable2Excel(DataTable dt, HSSFWorkbook workbook, string FilePath)
{
//创建sheet
ISheet sheet = workbook.CreateSheet("sheet1");
//设置header字体
HSSFCellStyle styleHeader = (HSSFCellStyle)workbook.CreateCellStyle();
styleHeader.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.Boldweight = (short)FontBoldWeight.Bold;
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(0);
for (int col = 0; col < dt.Columns.Count; col++)
{
ICell cellHeader = rowHeader.CreateCell(col);
cellHeader.SetCellValue(dt.Columns[col].ColumnName);
sheet.SetColumnWidth(col, 30 * 256);
cellHeader.CellStyle = styleHeader;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
cell.CellStyle = style;
}
}
workbook.Write(fs);
}
}
C# DataTable 数据导出为 Excel
最新推荐文章于 2025-04-07 17:05:27 发布