static void AddReportData(Worksheet worksheet)
{
worksheet.InsertDataTable(dataTable, true, 2, 1);//从第二行第一列的单元格开始插入一个dataTable,并将列头的数据也添加
CellStyle style = worksheet.Range["A2:J2"].Style;//获取A2到J2的单元格的格式
style.Font.Color = Color.White;//设置字体颜色为白色
style.KnownColor = ExcelColors.Green;//设置单元格的背景颜色为绿色
style.Font.IsBold = true;//设置字体加粗
style.HorizontalAlignment = HorizontalAlignType.Center;//设置文本水平居中
style.VerticalAlignment = VerticalAlignType.Center;//设置文本垂直居中
style.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;//设置左边的border
style.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;//设置右边的border
style.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;//设置上面的border
style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;//设置下面的border
CellStyle oddStyle = worksheet.Workbook.Styles.Add("oddStyle");//创建一个style并命名为"oddStyle"
oddStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
oddStyle.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
oddStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
oddStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
oddStyle.KnownColor = ExcelColors.LightGreen1;
CellStyle evenStyle = worksheet.Workbook.Styles.Add("evenStyle");//创建一个style并命名为"evenStyle"
evenStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
evenStyle.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
evenStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
evenStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
evenStyle.KnownColor = ExcelColors.LightTurquoise;
//为A3到J20的单元格设置格式,如果是奇数行使用oddStyle,如果是偶数行使用evenStyle
foreach (CellRange range in worksheet.Range["A3:J20"].Rows)
{
if (range.Row % 2 == 0)
range.CellStyleName = evenStyle.Name;
else
range.CellStyleName = oddStyle.Name;
}
worksheet.AllocatedRange.AutoFitColumns();//自动调整列的宽度去适应单元格的数据
worksheet.AllocatedRange.AutoFitRows();//自动调整行的高度去适应单元格的数据
}