问题:在使用hutool工具类ExcelWriter导出excel表格时,设置了自适应列宽格式,只有数字和字母生效,中文自适应列宽不生效,列宽只有差不多一半。
解决方法(同样适用于LINUX):
ExcelWriter writer = ExcelUtil.getWriter(true);
//写数据 writer.write(data, true);
StyleSet style = writer.getStyleSet();
Font font = writer.createFont();
font.setColor(IndexedColors.VIOLET.index);
font.setBold(true);
font.setFontHeightInPoints((short) 12);
//重点,设置中文字体
font.setFontName("宋体");
style.getHeadCellStyle().setFont(font);
int columnCount = writer.getColumnCount();
for (int i = 0; i < columnCount; ++i) {
double width = SheetUtil.getColumnWidth(writer.getSheet(), i, false);
if (width != -1.0D) {
width *= 256.0D;
//此处可以适当调整,调整列空白处宽度
width += 220D;
writer.setColumnWidth(i, Math.toIntExact(Math.round(width / 256D)));
}
}