public static void WriteExcel(System.Data.DataTable dt,string fileName)
{
NPOI.XSSF.UserModel.XSSFWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName);
NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
row.HeightInPoints = 25;
NPOI.SS.UserModel.ICellStyle headStyle = book.CreateCellStyle();
headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
headStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
headStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
headStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Justify;
headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.PaleBlue.Index;
headStyle.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
NPOI.SS.UserModel.IFont font = book.CreateFont();
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
headStyle.SetFont(font);
NPOI.SS.UserModel.ICellStyle style = book.CreateCellStyle();
style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Justify;
for (int i = 0; i < dt.Columns.Count; i++)
{
NPOI.SS.UserModel.ICell cell = row.CreateCell(i);
cell.CellStyle = headStyle;
cell.SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
row2.HeightInPoints = 20;
for (int j = 0; j < dt.Columns.Count; j++)
{
NPOI.SS.UserModel.ICell cell = row2.CreateCell(j);
cell.CellStyle = style;
cell.SetCellValue(Convert.ToString(dt.Rows[i][j]));
}
}
//自适应列宽度
for (int i = 0; i <= dt.Columns.Count; i++)
{
sheet.AutoSizeColumn(i);
}
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
book.Write(fs);
fs.Dispose();
book = null;
}
niop2.0.6