0

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

添加了换行符的表格单元格

选择特定单元格后,我用于此的代码:

cell.insertBefore("Test "+System.lineSeparator()+" Test");

以下也不起作用:

cell.insertBefore("Test "+System.getProperty("line.seperator")+" Test"); 
cell.insertBefore("Test \n Test");
cell.insertBefore("Test \r\n Test");

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

我还尝试将文档写入临时文件,然后用框替换占位符。HWPF -> empty有人知道解决方案吗?提前致谢。

4

1 回答 1

1

忘了apache poi HWPF。它在暂存器中,几十年来没有任何进展。并且没有可用的方法来插入或创建新段落。不只是文本的所有方法Range.insertBefore和方法都是私有的且已弃用,并且几十年来也无法正常工作。Range.insertAfter其原因可能是二进制文件格式Microsoft Word HWPF当然是所有其他可怕文件格式中最可怕的文件格式,HSSFHSLF. 那么谁愿意为此烦恼呢?

但要回答你的问题:

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

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

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

这会将文本运行“Test\u000BTest”放置在文档中每个表格的第一个单元格的第一段之前。并且该\u000B文本运行中的换行标记。

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

于 2021-08-13T09:47:43.957 回答