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

And*_*lyz 0 java excel apache-poi

我有固定的列宽,需要使用apache POI自动调整行高,但我找不到它的工作决定。我尝试过这个决定,但它不适用于此文本

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

在此输入图像描述

列宽为33.00(236 像素),表格中的单元格具有换行文本属性。仅当内容高度大于现有行高度时,我才能更改行高度。

那么,我想问是否有任何方法或决定可以按内容自动调整行高?

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;
}
Run Code Online (Sandbox Code Playgroud)

Axe*_*ter 5

只要该行不在合并区域内,如果未显式设置高度,它将自动调整高度。所以你需要将高度设置为未定义(-1)。请参阅Row.setHeight

设置行的高度或将未定义/默认高度设置为 ff (-1)。

完整示例:

来源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();
 }
}
Run Code Online (Sandbox Code Playgroud)

结果ExcelNew.xlsx

在此输入图像描述

如果您不知道哪些行必须是自动高度并且需要根据所需的高度来决定,那么您需要根据单元格宽度、文本和使用的字体来计算所需的高度。这是一项具有挑战性的任务。请参阅如何使用 Java 获取具有定义宽度的多行富文本字段(任何字体、任何字体大小)所需的高度?寻找可能的解决方案。