通过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);
}

效果如下

 

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