java poi调用excel文件的自动行高来设置自动行高

1,如果一行中没有合并单元格的单元格那就比较简单了可以直接调用api


XSSFWorkbook workbook = new XSSFWorkbook("文件路径或者文件流");

XSSFSheet sheet = workbook.getSheet(sheetIndex);

XSSFRow xssfRow = sheet.getRow(rowIndex);

CTRow ctRow = xssfRow.getCTRow();

ctRow.setCustomHeight(false);

2,如果有合并的单元格,因为excel不支持合并单元格自动行高就需要自己设计一下了。

得到简单思路就是计算合并单元格的总宽度和它的内容,然后把宽度设置在一个没有用到的单元格

把合并单元格的样式都复制在这个测试单元格内,内容也设置在该单元格内最后调用自动调整行高的api就可以准确得到行高了再把测试单元格删除掉就行了。而且比传统方法计算行高更加准确。大致代码如下不可直接用需要自己调整。

 public static void cellAndSetRowHeigt(Sheet sheet, XSSFRow sourceRow) {
        int count=1;
        int maxColumnIndex=30;
        for (int cellIndex = sourceRow.getFirstCellNum(); cellIndex <= sourceRow.getPhysicalNumberOfCells(); cellIndex++,count++) {
            if (cellIndex < 0) continue;
            XSSFCell sourceCell = sourceRow.getCell(cellIndex);
           //获取内容
            String cellContent = getCellContentAsString(sourceCell);
            if (null == cellContent || "".equals(cellContent)) {
                continue;
            }
            //得到列宽
            Map<String, Object> cellInfoMap = getCellInfo(sourceCell);
            Integer cellWidth = (Integer) cellInfoMap.get("width");
            if(getMergeColumNum(sourceCell,sheet)!=1){
                sheet.setColumnWidth(maxColumnIndex+count,cellWidth);
                XSSFCell cell = sourceRow.createCell(maxColumnIndex+ count);
                CellStyle newStyle = sheet.getWorkbook().createCellStyle();
                template2.copyCellStyle(sourceCell.getCellStyle(),newStyle,                                      sheet.getWorkbook());
                cell.setCellStyle(newStyle);
                //cell.getCellStyle().setFont(sourceCell.getCellStyle().getFont());
                cell.setCellValue(getCellContentAsString(sourceCell));
            }
        }
        sourceRow.getCTRow().setCustomHeight(false);
        for (int i=30;i<60;i++){
            sheet.setColumnHidden(i,true);
        }
    }

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值