通過poi+java實現Excel表格的列寬度自適應

// 新建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);
}

效果如下

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章