如何使用Apache POI在docx中用HTML替换文本(标签)?

最大限度

我们将有一些模板 docx 文件,其中会有一些标签,如 ${content}。我需要用 HTML 替换这个标签。

为此,我想在 XWPFDocument 中使用 altChunk 元素。按照How to add an altChunk element to a XWPFDocument using Apache POI 中的回答,我可以将 altChunk 放在 docx 的末尾。

我怎样才能用它替换我的标签?或者我可以使用任何其他库,可能是 docx4j?

UPD:带有标签的模板 docx 文件由最终用户使用 MS Word 创建,如下所示:示例 docx 模板

阿克塞尔·里希特

如果“${content}”在它自己IBodyElement中,则可以通过查找IBodyElement、创建XmlCursor、插入altChunk、然后删除IBodyElement解决该要求

以下代码通过扩展如何使用 Apache POI 将 altChunk 元素添加到 XWPFDocument 中的示例演示这一点它提供了一种用引用 a 的 a替换IBodyElement包含特殊文本的 found 的方法它用于获取文本正文中所需的位置。的用法在代码有注释。altChunkMyXWPFHtmlDocumentXmlCursorXmlCursor

模板.docx:

在此处输入图片说明

代码:

import java.io.*;

import org.apache.poi.*;
import org.apache.poi.ooxml.*;
import org.apache.poi.openxml4j.opc.*;

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

import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAltChunk;

public class WordInsertHTMLaltChunkInDocument {

 //a method for creating the htmlDoc /word/htmlDoc#.html in the *.docx ZIP archive  
 //String id will be htmlDoc#.
 private static MyXWPFHtmlDocument createHtmlDoc(XWPFDocument document, String id) throws Exception {
  OPCPackage oPCPackage = document.getPackage();
  PackagePartName partName = PackagingURIHelper.createPartName("/word/" + id + ".html");
  PackagePart part = oPCPackage.createPart(partName, "text/html");
  MyXWPFHtmlDocument myXWPFHtmlDocument = new MyXWPFHtmlDocument(part, id);
  document.addRelation(myXWPFHtmlDocument.getId(), new XWPFHtmlRelation(), myXWPFHtmlDocument);
  return myXWPFHtmlDocument;
 }

 //a method for replacing a IBodyElement containing a special text with CTAltChunk which
 //references MyXWPFHtmlDocument
 private static void replaceIBodyElementWithAltChunk(XWPFDocument document, String textToFind, 
                                                     MyXWPFHtmlDocument myXWPFHtmlDocument) throws Exception {
  int pos = 0;
  for (IBodyElement bodyElement : document.getBodyElements()) {
   if (bodyElement instanceof XWPFParagraph) {
    XWPFParagraph paragraph = (XWPFParagraph)bodyElement;
    String text = paragraph.getText();
    if (text != null && text.contains(textToFind)) {
     //create XmlCursor at this paragraph
     XmlCursor cursor = paragraph.getCTP().newCursor();
     cursor.toEndToken(); //now we are at end of the paragraph
     //there always must be a next start token. Either a p or at least sectPr.
     while(cursor.toNextToken() != org.apache.xmlbeans.XmlCursor.TokenType.START);
     //now we can insert the CTAltChunk here
     String uri = CTAltChunk.type.getName().getNamespaceURI();
     cursor.beginElement("altChunk", uri);
     cursor.toParent();
     CTAltChunk cTAltChunk = (CTAltChunk)cursor.getObject();
     //set the altChunk's Id to reference the given MyXWPFHtmlDocument
     cTAltChunk.setId(myXWPFHtmlDocument.getId());

     //now remove the found IBodyElement
     document.removeBodyElement(pos);

     break; //break for each loop
    }
   }
   pos++;
  }
 }

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

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

  MyXWPFHtmlDocument myXWPFHtmlDocument = createHtmlDoc(document, "htmlDoc1");
  myXWPFHtmlDocument.setHtml(myXWPFHtmlDocument.getHtml().replace("<body></body>",
   "<body><p>Simple <b>HTML</b> <i>formatted</i> <u>text</u></p></body>"));

  replaceIBodyElementWithAltChunk(document, "${content}", myXWPFHtmlDocument);

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

 }

 //a wrapper class for the  htmlDoc /word/htmlDoc#.html in the *.docx ZIP archive
 //provides methods for manipulating the HTML
 //TODO: We should *not* using String methods for manipulating HTML!
 private static class MyXWPFHtmlDocument extends POIXMLDocumentPart {

  private String html;
  private String id;

  private MyXWPFHtmlDocument(PackagePart part, String id) throws Exception {
   super(part);
   this.html = "<!DOCTYPE html><html><head><style></style><title>HTML import</title></head><body></body>";
   this.id = id;
  }

  private String getId() {
   return id;
  }

  private String getHtml() {
   return html;
  }

  private void setHtml(String html) {
   this.html = html;
  }

  @Override
  protected void commit() throws IOException {
   PackagePart part = getPackagePart();
   OutputStream out = part.getOutputStream();
   Writer writer = new OutputStreamWriter(out, "UTF-8");
   writer.write(html);
   writer.close();
   out.close();
  }

 }

 //the XWPFRelation for /word/htmlDoc#.html
 private final static class XWPFHtmlRelation extends POIXMLRelation {
  private XWPFHtmlRelation() {
   super(
    "text/html", 
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk", 
    "/word/htmlDoc#.html");
  }
 }
}

结果.docx:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何使用jQuery在HTML或XML文档的两个标签之间查找和替换文本?

来自分类Dev

如何使用jQuery在HTML或XML文档的两个标签之间查找和替换文本?

来自分类Dev

如何在excel中用数值替换文本

来自分类Dev

如何在powerquery中用null替换文本?

来自分类Dev

如何获取文本并在某些标签之间替换文本

来自分类Dev

替换 .docx 中的文本模板(Apache POI、Docx4j 或其他)

来自分类Dev

如何在Python中用空格替换文本中的特殊字符?

来自分类Dev

如何在谷歌应用程序脚本中用正则表达式替换文本

来自分类Dev

如何在 Linux 中用美元符号 $ 替换文本字符串?

来自分类Dev

如何使用apache poi在docx中编写混合文本(普通和下标)?

来自分类Dev

在 NodeJS 中使用 Cheerio 用 HTML 替换文本

来自分类Dev

Excel:如何使用通配符替换文本?

来自分类Dev

如何使用Apache POI将.docx转换为.doc

来自分类Dev

如何使用Apache Poi在Android上阅读.docx

来自分类Dev

使用Powershell替换文本

来自分类Dev

使用JQuery替换文本

来自分类Dev

使用php替换文本

来自分类Dev

使用Jquery替换文本

来自分类Dev

使用通配符替换文本

来自分类Dev

使用JQuery替换文本

来自分类Dev

如何替换html标签之间的任何文本

来自分类Dev

如何使用Apache POI PPT API设置文本字体?

来自分类Dev

如何使用 Apache POI 添加上标文本

来自分类Dev

使用`Replace()`方法不会替换Apache POI中的文本

来自分类Dev

如何在OSGi中使用Apache POI

来自分类Dev

如何在Apache Poi上使用子表?

来自分类Dev

如何使用Apache POI删除行

来自分类Dev

如何使用Apache POI读取特定行?

来自分类Dev

如何使用Apache POI删除行

Related 相关文章

热门标签

归档