// 新建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);
}
效果如下