maven 依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.15.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.15.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.15.0</version>
</dependency>
字体样式
public static Font demoFont(Workbook workbook) {
Font font = workbook.createFont();
font.setFontName("等线");
font.setFontHeightInPoints((short) 14);
font.setBold(true);
font.setColor(IndexedColors.BLACK.getIndex());
font.setItalic(true);
font.setStrikeout(true);
return font;
}
单元格样式
public static CellStyle demoStyle(Workbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(demoFont(workbook));
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setWrapText(true);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(new XSSFColor(new Color(181, 230, 181),new DefaultIndexedColorMap()));
return cellStyle;
}
设置列宽
sheet.autoSizeColumn(c);
sheet.setColumnWidth(c, 50 * 256);
给Sheet页设置格式通俗处理
public static void buildStyle(Workbook wb) {
Sheet sheet;
Row row;
for (int s = 0; s < wb.getNumberOfSheets(); s++) {
sheet = wb.getSheetAt(s);
for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
row = sheet.getRow(r);
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
if (r == 0) {
row.getCell(c).setCellStyle(headerStyle(wb));
sheet.autoSizeColumn(c);
} else {
row.getCell(c).setCellStyle(cellsStyle(wb));
if (sheet.getColumnWidth(c) > 50 * 256) {
sheet.setColumnWidth(c, 50 * 256);
}
}
}
}
}
}
参考
POI 导出 Excel 并且根据内容设置列宽自适应