POI设置自适应列宽(中文支持)
#实现代码
//poi设置自适应列宽
private void setColumnWidth(HSSFSheet sheet) {
//sheet的索引从0开始,获取sheet列数
int maxColumn = sheet.getRow(0).getPhysicalNumberOfCells();
/**第一种,实现自动换行,但不适用于中文
for (int i = 0; i < maxColumn; i++) {
sheet.autoSizeColumn(i);
}
*/
//第二种
for (int columnNum = 0; columnNum <= maxColumn; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
// 遍历列的数据,获取这一列的最长字符串
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(columnNum) != null) {
HSSFCell currentCell = currentRow.getCell(columnNum);
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
//int length = currentCell.getStringCellValue().getBytes().length;
//上面是网上所有currentCell获取length答案,但试过后发现偏大,在一个文章下的评论区看到下面的计算,试了一下,列宽实现了自适应大小,还没搞懂原因
//length = (byte长度+string长度)/2,有了解的麻烦,麻烦留言解释一下,感谢!!
int length = (currentCell.getStringCellValue().getBytes(StandardCharsets.UTF_8).length + currentCell.toString().length()) / 2;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
//将最长的length*256设为列宽
// sheet.setColumnWidth((short)列数,(short)(length*256));
sheet.setColumnWidth(columnNum, columnWidth * 256);
}
}
参考链接:
https://blog.csdn.net/Pro_Mophy/article/details/81626119?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task