原文链接:https://blog.csdn.net/dragon9a/article/details/72818740
原文作者:dragon9a
在原文的基础上做了一点点的调整。
自动调整列宽度的方法:
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++){
Row currentRow;
if(sheet.getRow(rowNum) == null){
currentRow = sheet.createRow(rowNum);
}else{
currentRow = sheet.getRow(rowNum);
}
if(currentRow.getCell(columnNum) != null){
Cell currentCell = currentRow.getCell(columnNum);
try {
int length = currentCell.toString().getBytes("GBK").length;
if(columnWidth < length + 1){
columnWidth = length + 8;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
sheet.setColumnWidth(columnNum, columnWidth * 256);
}
经测试可行,再也不用手动设置烦人的列宽度了,真爽!