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

安德鲁·苏利兹

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

Lorem ipsum dolor sat amet, consectetur adipiscing elit, sed 时间和活力,让劳动和悲伤,一些重要的事情做eiusmod

在此处输入图片说明

列宽为33.00(236 像素),表格中的单元格具有自动换行属性。只有当内容高度超过现有行高时,我才能更改行高。

所以,我想问一下是否有任何方法或desicions可以按内容自动调整行高?

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

对于未定义/默认高度,设置行的高度或设置为 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();
 }
}

结果ExcelNew.xlsx

在此处输入图片说明

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章