java - 使用Apache POI替换docx文本框中的文本

标签 java apache ms-word apache-poi

我正在使用 Apache POI 来替换 docx 的单词。对于普通的段落,我成功地使用了 XWPFParagraph 和 XWPFRun 来替换单词。然后我尝试替换文本框中的单词。我引用了这个 https://stackoverflow.com/a/25877256获取文本框中的文本。我成功地在控制台中打印了文本。但是,我未能替换文本框中的单词。
这是我的一些代码:

    for (XWPFParagraph paragraph : doc.getParagraphs()) {
        XmlObject[] textBoxObjects =  paragraph.getCTP().selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' declare namespace wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' .//*/wps:txbx/w:txbxContent");
            for (int i =0; i < textBoxObjects.length; i++) {
                XWPFParagraph embeddedPara = null;
                try {
                XmlObject[] paraObjects = textBoxObjects[i].
                    selectChildren(
                    new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "p"));

                for (int j=0; j<paraObjects.length; j++) {
                    embeddedPara = new XWPFParagraph(CTP.Factory.parse(paraObjects[j].xmlText()), paragraph.getBody());
                    List<XWPFRun> runs = embeddedPara.getRuns();
                    for (XWPFRun r : runs) {
                        String text = r.getText(0);
                        if (text != null && text.contains(someWords)) {
                            text = text.replace(someWords, "replaced");
                            r.setText(text, 0);
                        }
                    }
                } 
                } catch (XmlException e) {
                //handle
                }
            }
    }

我认为问题在于我创建了一个新的 XWPFParagraph embeddingPara 并且它替换了 EmbeddedPara 的单词而不是原始段落。所以在我写入文件后,单词仍然没有改变。

如何在不创建新的 XWPFParagraph 的情况下读取和替换文本框中的单词?

最佳答案

出现问题的原因是 Word文本框可能包含在多个不同的 XmlObjects 中依赖于 Word版本。那些XmlObjects也可能在非常不同的 namespace 中。所以selectChildren无法遵循命名空间路由,因此它将返回 XmlAnyTypeImpl .

所有文本框实现的共同点是它们的运行都在路径 .//*/w:txbxContent/w:p/w:r 中。 .所以我们可以使用 XmlCursor选择该路径。然后我们收集所有被选中的XmlObjectsList<XmlObject> .然后我们解析 CTR s 来自这些对象,当然只有 CTR s 在文档上下文之外。但是我们可以创建 XWPFRuns从那些,在那里进行更换,然后 set那些 XWPFRuns 的 XML 内容回到对象。在此之后,我们有包含替换内容的对象。

例子:

enter image description here

import java.io.FileOutputStream;
import java.io.FileInputStream;

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

import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor;

import  org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;

import java.util.List;
import java.util.ArrayList;

public class WordReplaceTextInTextBox {

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

  XWPFDocument document = new XWPFDocument(new FileInputStream("WordReplaceTextInTextBox.docx"));

  String someWords = "TextBox";

  for (XWPFParagraph paragraph : document.getParagraphs()) {
   XmlCursor cursor = paragraph.getCTP().newCursor();
   cursor.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//*/w:txbxContent/w:p/w:r");

   List<XmlObject> ctrsintxtbx = new ArrayList<XmlObject>();

   while(cursor.hasNextSelection()) {
    cursor.toNextSelection();
    XmlObject obj = cursor.getObject();
    ctrsintxtbx.add(obj);
   }
   for (XmlObject obj : ctrsintxtbx) {
    CTR ctr = CTR.Factory.parse(obj.xmlText());
    //CTR ctr = CTR.Factory.parse(obj.newInputStream());
    XWPFRun bufferrun = new XWPFRun(ctr, (IRunBody)paragraph);
    String text = bufferrun.getText(0);
    if (text != null && text.contains(someWords)) {
     text = text.replace(someWords, "replaced");
     bufferrun.setText(text, 0);
    }
    obj.set(bufferrun.getCTR());
   }
  }

  FileOutputStream out = new FileOutputStream("WordReplaceTextInTextBoxNew.docx");
  document.write(out);
  out.close();
  document.close();
 }
}

enter image description here

关于java - 使用Apache POI替换docx文本框中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46802369/

相关文章:

php - 400 : Bad Request !

python - Django (mod_wsgi) 处理 WSGI 脚本时发生异常

c++ - 纯 C++ 中的 Word 自动化

java - 如何在不暴露密码的情况下连接到需要密码的数据库?

javascript - 变量未使用 RESTful 传递到后端

java - 升级到 Gradle 6 后,Jenkins 控制台上未打印上传的 War 或 Tar 信息

java - 如何使用 JACOB 更改 Activity 的 MS Word 窗口?

java - 使用基于菜单的程序的日期格式和数组

apache - 如果请求来自特定主机,则特定 URL 重定向到 http

excel - 我想从word中提取段落并将其导入到excel电子表格中的单元格中,保留项目符号和字母