:编辑开始:
如果有人偶然发现了这个问题,请注意一下。
让 newLines 工作后,我想设置行高以匹配内容。为此,我只需将行高设置为 cellValue 中的新行数。 但是,在使用 poi 创建电子表格时,在 cellValue 之前或之后应用 cellStyle 似乎很重要。在我的例子中,它只有在我应用 cellStyle before 添加 cellValue 时才有效。
哦,记住 rowHeight 被定义为一个字符的 1/256(!?!?!)所以将 rowHeight 设置为
(short)(numberOfNewLines*256)
:编辑结束:
我有这段代码可以生成 Excel 电子表格。一些单元格的内容是使用
创建的cell.setCellValue(new XSSFRichTextString(header));
cell.setCellStyle(cs);
但是如果我设置
header = "Estimated\nDuration";
然后新行不会呈现在生成的电子表格中。它只是作为“EstimatedDuration”出现。
我正在使用 Apache POI v3.9。
有什么建议吗?
最佳答案
让我们从如何使用 Excel 在 Excel 电子表格中添加换行符开始。根据this article ,编辑单元格内容,将光标放在所需的换行符位置,然后执行 Alt + Enter。这样做的效果是在字符串中引入一个换行符并在单元格中打开“Wrap Text”。
您的字符串中已经有了换行符,但您需要添加到代码中以修改您的 CellStyle
以打开换行文本,使用 setWrapText
method .
String header = "Estimated\nDuration";
cell.setCellValue(new XSSFRichTextString(header));
// Add this line to turn on wrapped text.
cs.setWrapText(true);
cell.setCellStyle(cs);
这似乎在 .xls 和 .xlsx 文件上测试成功。
如果单元格样式的“wrap text”属性设置为 true
,Excel 似乎只会换行,是否存在换行符。
关于java - XSSFRichTextString 中忽略新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25759047/