POI设置自适应列宽(中文支持),非原创

POI设置自适应列宽(中文支持)

#实现代码

    //poi设置自适应列宽
    private void setColumnWidth(HSSFSheet sheet) {
        //sheet的索引从0开始,获取sheet列数
        int maxColumn = sheet.getRow(0).getPhysicalNumberOfCells();
        /**第一种,实现自动换行,但不适用于中文
         for (int i = 0; i < maxColumn; i++) {
         sheet.autoSizeColumn(i);
         }
         */
        //第二种
        for (int columnNum = 0; columnNum <= maxColumn; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            // 遍历列的数据,获取这一列的最长字符串
            for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(columnNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        //int length = currentCell.getStringCellValue().getBytes().length;
                        //上面是网上所有currentCell获取length答案,但试过后发现偏大,在一个文章下的评论区看到下面的计算,试了一下,列宽实现了自适应大小,还没搞懂原因
                        //length = (byte长度+string长度)/2,有了解的麻烦,麻烦留言解释一下,感谢!!
                        int length = (currentCell.getStringCellValue().getBytes(StandardCharsets.UTF_8).length + currentCell.toString().length()) / 2;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            //将最长的length*256设为列宽
            // sheet.setColumnWidth((short)列数,(short)(length*256));
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }

参考链接:
https://blog.csdn.net/Pro_Mophy/article/details/81626119?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值