3

我正在尝试从 Microsoft Word 文档中删除一组连续的段落,使用Apache POI.

据我了解,可以通过删除所有运行来删除段落,这种方式:

/*
 * Deletes the given paragraph.
 */
public static void deleteParagraph(XWPFParagraph p) {
    if (p != null) {
        List<XWPFRun> runs = p.getRuns();
        //Delete all the runs
        for (int i = runs.size() - 1; i >= 0; i--) {
            p.removeRun(i);
        }
        p.setPageBreak(false); //Remove the eventual page break
    }
}

事实上,它有效,但有些奇怪。删除的段落块不会从文档中消失,但会转换为一组空行。就像每个段落都将转换为新行一样。

通过从代码中打印段落的内容,我实际上可以看到一个空格(对于每个删除的空格)。直接从文档中查看内容,启用格式标记的可视化,我可以看到:

在此处输入图像描述

¶ 的垂直列对应于已删除元素的块。

你对此有什么想法吗?我希望我的段落被完全删除。

我还尝试通过替换文本(用setText())并删除可以自动添加的最终空格,这样:

p.setSpacingAfter(0);
p.setSpacingAfterLines(0);
p.setSpacingBefore(0);
p.setSpacingBeforeLines(0);
p.setIndentFromLeft(0);
p.setIndentFromRight(0);
p.setIndentationFirstLine(0);
p.setIndentationLeft(0);
p.setIndentationRight(0);

但没有运气。

4

2 回答 2

7

我会通过删除段落来删除段落,而不是仅删除本段中的运行。删除段落不是apache poi高级 API 的一部分。但是使用XWPFDocument.getDocument().getBody()我们可以获得低级别CTBody并且有一个removeP(int i).

例子:

import java.io.*;
import org.apache.poi.xwpf.usermodel.*;

import java.awt.Desktop;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

public class WordRemoveParagraph {

 /*
  * Deletes the given paragraph.
  */

 public static void deleteParagraph(XWPFParagraph p) {
  XWPFDocument doc = p.getDocument();
  int pPos = doc.getPosOfParagraph(p);
  //doc.getDocument().getBody().removeP(pPos);
  doc.removeBodyElement(pPos);
 }

 public static void main(String[] args) throws IOException, InvalidFormatException {

  XWPFDocument doc = new XWPFDocument(new FileInputStream("source.docx"));

  int pNumber = doc.getParagraphs().size() -1;
  while (pNumber >= 0) {
   XWPFParagraph p = doc.getParagraphs().get(pNumber);
   if (p.getParagraphText().contains("delete")) {
    deleteParagraph(p);
   }
   pNumber--;
  }

  FileOutputStream out = new FileOutputStream("result.docx");
  doc.write(out);
  out.close();
  doc.close();

  System.out.println("Done");
  Desktop.getDesktop().open(new File("result.docx"));

 }

}

这将删除文档 source.docx 中文本包含“delete”的所有段落,并将结果保存在 result.docx 中。


编辑:

虽然doc.getDocument().getBody().removeP(pPos);有效,但它不会更新XWPFDocument的段落列表。因此它将破坏段落迭代器和对该列表的其他访问,因为该列表仅在再次阅读文档时才更新。

所以更好的方法是使用doc.removeBodyElement(pPos);removeBodyElement(int pos)的作用与指向文档正文中的 pagagraph 完全相同,因为doc.getDocument().getBody().removeP(pos);pos段落也是 an BodyElement。但除此之外,它还会更新XWPFDocument的段落列表。

于 2016-10-31T17:18:42.413 回答
1

当您在表格内时,您需要使用以下功能XWPFTableCell而不是XWPFDocument

cell.removeParagraph(cell.getParagraphs().indexOf(para));
于 2017-04-13T11:05:23.540 回答