如您所见,“使用正则表达式(java RegEx)在MS Word(.docx)文档中进行替换”的方法并不是很好,因为您永远无法确定要替换的文本会在一个文本运行中一起出现。 更好的方法是在Word中使用字段(合并字段或表单字段)或内容控件。
对于此类要求,我的最爱仍然是Word好的旧表单字段。
第一个优点是,即使没有文档保护,也无法格式化表单字段内容的不同部分,因此将表单字段内容拆分为不同的行(但请参见注释1)。 第二个优点是,由于背景为灰色,因此表单字段在文档内容中清晰可见。 另一个优点是可以应用文档保护,以便即使在Word的GUI中也只能填写表格字段。 这对于保留此类合同文档免于不必要的更改确实非常有用。
(注1):至少Word阻止格式化表单字段内容的不同部分,因此将表单字段内容拆分为不同的行。 但是其他文字处理软件(例如Writer )可能不遵守此限制。
因此,我将拥有这样的Word模板:
灰色字段是Word好的旧格式Textfield ,分别称为Text1 , Text2和Text3 。 文本字段块如下所示:
...
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
... >
然后是下面的代码:
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.apache.xmlbeans.SimpleValue;
import javax.xml.namespace.QName;
public class WordReplaceTextInFormFields {
private static void replaceFormFieldText(XWPFDocument document, String ffname, String text) {
boolean foundformfield = false;
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
XmlCursor cursor = run.getCTR().newCursor();
cursor.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:fldChar/@w:fldCharType");
while(cursor.hasNextSelection()) {
cursor.toNextSelection();
XmlObject obj = cursor.getObject();
if ("begin".equals(((SimpleValue)obj).getStringValue())) {
cursor.toParent();
obj = cursor.getObject();
obj = obj.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:ffData/w:name/@w:val")[0];
if (ffname.equals(((SimpleValue)obj).getStringValue())) {
foundformfield = true;
} else {
foundformfield = false;
}
} else if ("end".equals(((SimpleValue)obj).getStringValue())) {
if (foundformfield) return;
foundformfield = false;
}
}
if (foundformfield && run.getCTR().getTList().size() > 0) {
run.getCTR().getTList().get(0).setStringValue(text);
//System.out.println(run.getCTR());
}
}
}
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument(new FileInputStream("WordTemplate.docx"));
replaceFormFieldText(document, "Text1", "Моя Компания");
replaceFormFieldText(document, "Text2", "Аксель Джоачимович Рихтер");
replaceFormFieldText(document, "Text3", "Доверенность");
FileOutputStream out = new FileOutputStream("WordReplaceTextInFormFields.docx");
document.write(out);
out.close();
document.close();
}
}
此代码需要FAQ-N10025中提到的所有架构ooxml-schemas-1.3.jar的完整jar。
产生: