准备文档如下
image.png
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class TextReplacement {
public static void main(String[] args) throws Exception {
String dir = System.getProperty("user.dir");
String filePath = dir + "/template/template.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(filePath));
Map<String, String> mappings = new HashMap<String, String>();
mappings.put("name", "姓名");
mappings.put("sex", "性别");
mappings.put("age", "12");
//设置全局的变量替换
wordMLPackage.getMainDocumentPart().variableReplace(mappings);
String out = dir + "/out.docx";
Docx4J.save(wordMLPackage, new File(out));
}
}
输出如下
image.png
word文档格式复杂,使用以上方式替换文本需特别注意,使用时建议做测试
网友评论