easypoi动态设置列宽,解决自动设置列宽失效

问题场景:
最近开发,使用easypoi导出excel时,需要动态定义列表的宽度,
实际使用列宽自适应方法sheet.AutoSizeColumn(i);时,无法满足实际所需,该方法只能解决英文、数字列宽自适应,如果该列为中文,会出现列宽不足现象。

解决办法:
使用方法sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);

/**
     * 设置列宽
     * 使用列宽自适应方法sheet.AutoSizeColumn(i);
     * 只能解决英文、数字列宽自适应,如果该列为中文,会出现列宽不足现象。
     * 解决方法:
     * - 1、先使用POI提供的列宽自适应方法sheet.autoSizeColumn(i)
     * - 2、再使用方法sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
     *
     * @param sheet : sheet
     * @author cp218
     * @date 2024/1/31 16:52
     */
private static void autoSizeHeader(Sheet sheet) {
        Row headerRow = sheet.getRow(0);
        if (headerRow != null) {
            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    CellStyle cellStyle = cell.getCellStyle();
                    // 取消自动换行
                    cellStyle.setWrapText(false);
                    // 根据表头字段设置列宽
                    // int width = cell.getStringCellValue().length() * 750;
                    // sheet.setColumnWidth(i, width);
                }
                // 1、先设置自动列宽
                sheet.autoSizeColumn(i);
                // 2、再手动设置列宽度,设置列宽为自动列宽的1.7倍,为什么是1.7倍?(经过测试所得,也可以是1.5倍、1.6倍)
                int width = sheet.getColumnWidth(i) * 17 / 10;
                sheet.setColumnWidth(i, width);
            }
        }
    }
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值