private static void ToEXecl(DataTable tblDatas)
{
String strFileName = "F:/excel/BBS.xls";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("new sheet");
// 设置列宽
sheet.SetColumnWidth(0,1500);
sheet.SetColumnWidth(1, 8000);
sheet.SetColumnWidth(2, 4000);
sheet.SetColumnWidth(3, 5000);
sheet.SetColumnWidth(4, 5000);
sheet.SetColumnWidth(5, 16000);
sheet.SetColumnWidth(6, 3000);
sheet.SetColumnWidth(7, 6000);
sheet.SetColumnWidth(8, 12000);
HSSFFont font1 = workbook.CreateFont();
font1.FontName="宋体";
font1.FontHeightInPoints=16;
//表头样式
HSSFCellStyle style1 = workbook.CreateCellStyle();
//颜色要两行
style1.FillForegroundColor = HSSFColor.YELLOW.index;
style1.FillPattern = CellFillPattern.SOLID_FOREGROUND;
//设置单元格边框
style1.BorderBottom = CellBorderType.THIN;
style1.BorderLeft = CellBorderType.THIN;
style1.BorderRight = CellBorderType.THIN;
style1.BorderTop = CellBorderType.THIN;
style1.SetFont(font1);
HSSFFont font2 = workbook.CreateFont();
font2.FontName = "宋体";
//内容样式
HSSFCellStyle style2 = workbook.CreateCellStyle();
style2.SetFont(font2);
//设置换行
style2.WrapText = true;
HSSFFont font3 = workbook.CreateFont();
font3.Color = HSSFColor.DARK_BLUE.index;
HSSFCellStyle style3 = workbook.CreateCellStyle();
style3.WrapText = true;
style3.SetFont(font3);
//填充表头
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0);
foreach (DataColumn column in tblDatas.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
dataRow.Height = 600;
dataRow.GetCell(column.Ordinal).CellStyle = style1;
}
//填充内容
for (int i = 0; i < tblDatas.Rows.Count; i++)
{
dataRow = sheet.CreateRow(i + 1);
dataRow.Height = 500;
for (int j = 0; j < tblDatas.Columns.Count;
j++)
{
dataRow.CreateCell(j).SetCellValue(tblDatas.Rows[i][j].ToString());
dataRow.GetCell(j).CellStyle = style2;
}
dataRow.GetCell(5).CellStyle = style3;
}
//保存
using (MemoryStream ms = new MemoryStream())
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create,
FileAccess.Write))
{
workbook.Write(fs);
}
}
workbook.Dispose();
}