Apache POI 和按内容自动调整 XSSFRow 高度

Apache POI and autofit XSSFRow heigth by content

我有固定的列宽,需要使用 apache POI 自动调整行高,但我找不到适用的方法。我试过 this decision,但它不适用于此文本

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

列宽为 33.00(236 像素),table 中的单元格 wrap text 属性。只有当内容高度大于行的现有高度时,我才能更改行高。

所以,我想请问有没有什么方法或方法可以根据内容自动调整行高?

private float calculateRowLinesForText(Font cellFont, float columnWidthInPoints, String value) {
        java.awt.Font currFont = new java.awt.Font(cellFont.getFontName(), 0, cellFont.getFontHeightInPoints());

        FontRenderContext frc = new FontRenderContext(null, true, true);

        int lineCnt = 0;
        for (String partValue : value.split("\n")) {
            AttributedString attrStr = new AttributedString(partValue);
            attrStr.addAttribute(TextAttribute.FONT, currFont);
            LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(), frc);

            while (measurer.getPosition() < partValue.length()) {
                int nextPos = measurer.nextOffset(columnWidthInPoints);
                lineCnt++;
                measurer.setPosition(nextPos);
            }
        }

        return lineCnt;
}

只要该行不在合并区域内,如果未明确设置高度,它就会自动调整高度。所以你需要将高度设置为未定义(-1)。见 Row.setHeight:

Set the row's height or set to ff (-1) for undefined/default-height.

完整示例:

来源Excel.xlsx:

代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;

public class CreateExcelCellWrapText {

 public static void main(String[] args) throws Exception {
  Workbook workbook = WorkbookFactory.create(new FileInputStream("./Excel.xlsx"));

  Sheet sheet = workbook.getSheetAt(0);
  
  Row row = sheet.getRow(2);
  Cell cell = row.getCell(2); // cell C3
  cell.setCellValue("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua");
  CellUtil.setCellStyleProperty(cell, CellUtil.WRAP_TEXT, true); // make sure wrap text is set.
  row.setHeight((short)-1); // set row heigth undefined so it is auto heigth

  FileOutputStream out = new FileOutputStream("./ExcelNew.xlsx");
  workbook.write(out);
  out.close();
  workbook.close();
 }
}

结果ExcelNew.xlsx:

如果您不知道哪些行必须是自动高度并且需要根据所需的高度来决定,那么您需要根据单元格宽度、文本和使用的字体来计算所需的高度。这是一项具有挑战性的任务。有关可能的解决方案,请参阅 How to get the needed height of a multi line rich-text field (any font, any font size) having defined width using Java?