設置文檔默認為無邊框
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());
}
}