1.api提供了自适应宽度
2.自测部分
有部分说autoSizeColumnAll 放置的位置应该在完全写入的后面
//一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
自测:autoSizeColumnAll 放在write上面影响header的自适应
放在write下面都不起作用
解决方式:
writer.write(list, true); 后面加上:
setSizeColumn(writer.getSheet());
public static void setSizeColumn(Sheet sheet) {
for (int columnNum = 0; columnNum <= 0; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
Row currentRow = row == null ? sheet.createRow(rowNum) : row;
if (currentRow.getCell(columnNum) != null) {
Cell currentCell = currentRow.getCell(columnNum);
if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
sheet.setColumnWidth(columnNum, columnWidth * 256);
}
}
评论区处理方法:
/**
* 自动设置列宽,取前15 rows 作为样本,解决卡顿和不生效
* @see SheetUtil#getColumnWidth(Sheet, int, boolean, int, int)
*/
public static void setColumnWidth(ExcelWriter writer) {
// 因 column 的计算依赖字体设置,so,必先设置字体后再设列宽
setFont(writer);
final Sheet sheet = writer.getSheet();
int lastRow = Math.min(writer.getRowCount(), 16) - 1;
for (int i = 0; i < writer.getColumnCount(); i++) {
writer.setColumnWidth(i, (int) SheetUtil.getColumnWidth(sheet, i, false, 0, lastRow));
}
}
// 字体:Consolas
private static void setFont(ExcelWriter writer) {
final Workbook wb = writer.getWorkbook();
final StyleSet styleSet = writer.getStyleSet();
final Font headFont = createFont(wb, Font.COLOR_NORMAL, (short) 12, "Consolas"),
cellFont = createFont(wb, Font.COLOR_NORMAL, (short) 11, "Consolas");
styleSet.setFont(headFont, false);
styleSet.setFont(cellFont, true);
}