XSSFRichTextString 中的新行被忽略 [英] New line ignored in XSSFRichTextString

查看:82
本文介绍了XSSFRichTextString 中的新行被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:编辑开始:

如果有人偶然发现这个问题,那么这里有一个小小的提醒.

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

在让 newLines 工作后,我想设置行高以匹配内容.为此,我只需将行高设置为 cellValue 中的新行数.但是,在使用 poi 创建电子表格时,在 cellValue 之前或之后应用 cellStyle 似乎很重要.就我而言,它仅在我应用 cellStyle before 添加 cellValue 时才有效.

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.

哦,记住 rowHeight 被定义为一个字符的 1/256(!?!?!) 所以将 rowHeight 设置为

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

(short)(numberOfNewLines*256)

:编辑结束:

我有一段生成 Excel 电子表格的代码.一些单元格的内容是使用

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);

但是如果我设置

header = "Estimated\nDuration";

那么新行不会在生成的电子表格中呈现.它只是显示为估计持续时间".

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

我使用的是 Apache POI v3.9.

I'm using Apache POI v3.9.

有什么建议吗?

推荐答案

让我们从如何使用 Excel 在 Excel 电子表格中放置换行符开始.根据 这篇文章,编辑单元格内容,将光标置于所需的换行位置,然后按Alt + Enter.这样做的效果是在字符串中引入一个换行符打开单元格中的Wrap Text".

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.

您已经在字符串中添加了换行符,但是您需要添加到您的代码中以修改您的 CellStyle 以打开换行文本,并使用 setWrapText 方法.>

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);

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

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

如果单元格样式的换行文本"属性设置为 true,Excel 似乎只会换行,无论是否存在换行符.

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

这篇关于XSSFRichTextString 中的新行被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆