设置文档默认为无边框
ISheet sheet = book.CreateSheet(sheetName[i]);
sheet.DisplayGridlines = false;//设置默认为无边框
var head = sheet.CreateRow(0);
for (int a = 0; a < header.Count(); a++)
{
ICell cell = head.CreateCell(a);
XSSFCellStyle fCellStyle = (XSSFCellStyle)book.CreateCellStyle();
XSSFFont ffont = (XSSFFont)book.CreateFont();
ffont.FontHeight = 20 * 20;
ffont.FontHeightInPoints = (short)9.75;//字号
ffont.FontName = "Times New Roman";//字体
ffont.Color = HSSFColor.White.Index;//字色
fCellStyle.SetFont(ffont);
fCellStyle.FillPattern = FillPattern.SolidForeground;//添加背景色必须加这句
fCellStyle.FillForegroundColor = HSSFColor.Grey50Percent.Index;//设置背景填充色50%的灰色
fCellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直对齐
fCellStyle.Alignment = HorizontalAlignment.Center;//水平对齐
fCellStyle.BorderBottom = BorderStyle.Thin;//下边框为细线边框
fCellStyle.BorderLeft = BorderStyle.Thin;//左边框
fCellStyle.BorderRight = BorderStyle.Thin;//上边框
fCellStyle.BorderTop = BorderStyle.Thin;//右边框
fCellStyle.BottomBorderColor = HSSFColor.Grey25Percent.Index;//下边框为细线边框
fCellStyle.LeftBorderColor = HSSFColor.Grey25Percent.Index;//左边框
fCellStyle.RightBorderColor = HSSFColor.Grey25Percent.Index;//上边框
fCellStyle.TopBorderColor = HSSFColor.Grey25Percent.Index;//右边框
cell.CellStyle = fCellStyle;
cell.SetCellValue(header[a]);
}
for (int j = 0; j < datas[i].Count(); j++)
{
var row = sheet.CreateRow(j + 1);
if (row == null)
{
row = sheet.CreateRow(j + 1);
}
row.CreateCells(datas[i][j], styleBody);//styleBody
}
for (int columnNum = 0; columnNum < header.Count; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;//获取当前列宽度
for (int rowNum = 0; rowNum < sheet.LastRowNum; rowNum++)//在这一列上循环行
{
IRow currentRow = sheet.GetRow(rowNum);
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;//获取当前单元格的内容宽度
if (columnWidth < length)
{
columnWidth = length;
}//若当前单元格内容宽度大于列宽,则调整列宽为当前单元格宽度
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}
//行扩展方法填充数据设置并单元格样式(数据类型不可为空,否则会报空指针)
public static void CreateCells(this IRow row, object data, ICellStyle style = null)
{
Type t = data.GetType();
int i = 0;
foreach (var Propertie in t.GetProperties())
{
var cell = row.CreateCell(i++);
if (style != null)
{
cell.CellStyle = style;
}
cell.SetCellValue(Convert.ChangeType(Propertie.GetValue(data), Propertie.PropertyType).ToString());
}
}