且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在XSSFRichTextString中忽略新行

更新时间:2023-12-04 13:05:58

让我们首先介绍如何使用Excel在Excel电子表格中添加换行符。根据本文,编辑单元格内容,将光标放在所需的换行位置,然后执行 Alt + Enter 。这样做的结果是在字符串中引入换行符并在中打开单元格中的换行文本。



你有换行符字符串中的字符已经存在,但您需要添加到代码中以修改 CellStyle 以打开包装文本,并使用 setWrapText method

  String header =Estimated\\\
Duration;
cell.setCellValue(new XSSFRichTextString(header));

//添加此行以打开包装文本。
cs.setWrapText(true);

cell.setCellStyle(cs);

这似乎可以在.xls和.xlsx文件上成功测试。



如果单元格样式的换行文本属性设置为 true ,Excel似乎只会换行文本,换行是否存在。 / p>

:EDIT START:

Should anyone stumble across this q then here's a small heads up.

After getting newLines to work I wanted to set the row height to match the content. To do this I simply set the row height to the number of newLines in the cellValue. However when creating a spreadsheet using poi it seems to be matter if you apply the cellStyle before or after the cellValue. In my case it only worked if I apply the cellStyle before adding the cellValue.

Oh and remember that rowHeight is defined as 1/256 of a character(!?!?!) so set rowHeight to

(short)(numberOfNewLines*256)

:EDIT END:

I have this piece of code that generates an Excel spreadsheet. The contents of some of the cells are created using

cell.setCellValue(new XSSFRichTextString(header));
cell.setCellStyle(cs);

However if I set

header = "Estimated\nDuration";

then the new line is not rendered in the resulting spreadsheet. It just comes out as "EstimatedDuration".

I'm using Apache POI v3.9.

Any suggestions?

Let's start with how to put a newline in an Excel spreadsheet using Excel. According to this article, edit the cell contents, placing the cursor at the desired newline location, and do Alt + Enter. The effect of this is to introduce a newline character into the string and turn on "Wrap Text" in the cell.

You have the newline character in the string already, but you'll need to add to your code to modify your CellStyle to turn on wrapped text, with the 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);

This appears to test successfully on .xls and .xlsx files.

It appears that Excel will only wrap text, newline present or not, if the cell style has the "wrap text" property set to true.