忘了apache poi
HWPF
。它在暂存器中,几十年来没有任何进展。并且没有可用的方法来插入或创建新段落。不只是文本的所有方法Range.insertBefore
和方法都是私有的且已弃用,并且几十年来也无法正常工作。Range.insertAfter
其原因可能是二进制文件格式Microsoft Word
HWPF
当然是所有其他可怕文件格式中最可怕的文件格式,HSSF
如HSLF
. 那么谁愿意为此烦恼呢?
但要回答你的问题:
在文字处理中,文本由包含文本运行的段落构成。默认情况下,每个段落都会换行。但是存储在文本运行中的“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
. 下一个无法解决的问题仅一步之遥。