首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Apache POI HWPF文档中添加换行符,例如\\n

如何在Apache POI HWPF文档中添加换行符,例如\\n
EN

Stack Overflow用户
提问于 2021-08-12 12:55:21
回答 1查看 221关注 0票数 0

我必须修改旧的.doc格式的Word文档。将Apache POI与文档的HWPF表示一起使用。我很难在任何表格单元格中插入换行符。在修改后的文档中,换行符看起来像空框。

table cell with added line break

在选择了特定的单元格后,我使用的代码如下:

代码语言:javascript
复制
cell.insertBefore("Test "+System.lineSeparator()+" Test");

以下代码也不起作用:

代码语言:javascript
复制
cell.insertBefore("Test "+System.getProperty("line.seperator")+" Test"); 
cell.insertBefore("Test \n Test");
cell.insertBefore("Test \r\n Test");

我试过的所有东西都变成了盒子。

我还尝试将文档写入临时文件,然后用HWPF -> empty boxes.Does替换占位符。有人知道解决这个问题的方法吗?提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-13 09:47:44

忘了apache poi HWPF吧。它在便签簿中,几十年来没有任何进展。并且没有可用的方法来插入或创建新段落。所有不只接受文本的Range.insertBeforeRange.insertAfter方法都是私有的,几十年来也不推荐使用,也不能正常工作。原因可能是Microsoft Word HWPF的二进制文件格式当然是所有其他可怕的文件格式中最可怕的文件格式,如HSSFHSLF。那么,谁愿意为此而烦恼呢?

但要回答你的问题:

在字处理中,文本是以包含文本串的段落形式构成的。默认情况下,每个段落都换一行。但存储在文本串中的“text \n text”或“text\r text”或“text\r\n text”只会在该文本串中标记换行符,而不会标记新段落。因为Microsoft Word当然有它自己的规则。在文本串中,\u000B标记了换行符。

因此,您可以执行以下操作:

代码语言:javascript
复制
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.usermodel.*;

public class ReadAndWriteDOCTable {

 public static void main(String[] args) throws Exception {

  HWPFDocument document = new HWPFDocument(new FileInputStream("TemplateDOC.doc"));

  Range bodyRange = document.getRange();
  System.out.println(bodyRange);
  
  TableIterator tableIterator = new TableIterator(bodyRange);
  while (tableIterator.hasNext()) {
   Table table = tableIterator.next();
   System.out.println(table);
   TableCell cell = table.getRow(0).getCell(0); // first cell in table
   System.out.println(cell);
   Paragraph paragraph = cell.getParagraph(0); // first paragraph in cell
   System.out.println(paragraph); 
   CharacterRun run = paragraph.insertBefore("Test\u000BTest");
   System.out.println(run); 
  }
  
  FileOutputStream out = new FileOutputStream("ResultDOC.doc");
  document.write(out);
  out.close();
  document.close();
  
 }
}

这会将文本run "Test\u000BTest“放在文档中每个表的第一个单元格的第一个段落之前。\u000B在该文本串中标记一个换行符。

也许这就是你想要实现的目标?但是,如上所述,忘记apache poi HWPF吧。下一个无法解决的问题只有一步之遥。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68757906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档