// 新建sheet同時往sheet加入數據後,進行列寬設置,代碼如下:
// 固定首行,下拉時實現首行固定不動
sheet.createFreezePane( 0, 1, 0, 1 );
// 列寬自適應
// outputList.get(0).size()爲首行的列數,根據首行列數循環設置每一列的寬度
for (int columnIndex = 0; columnIndex < outputList.get(0).size(); columnIndex++) {
int columnWidth = sheet.getColumnWidth(columnIndex) / 256;
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
XSSFRow currentRow;
// 當前行未被使用過
if (sheet.getRow(rowIndex) == null) {
currentRow = sheet.createRow(rowIndex);
} else {
currentRow = sheet.getRow(rowIndex);
}
if (currentRow.getCell(columnIndex) != null) {
XSSFCell currentCell = currentRow.getCell(columnIndex);
if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
int length = 0;
try {
length = currentCell.getStringCellValue().getBytes().length;
} catch (Exception e) {
e.printStackTrace();
}
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
sheet.setColumnWidth(columnIndex, (columnWidth) * 256);
}
效果如下