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

效果如下

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值