準(zhǔn)備文檔如下
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");
//設(shè)置全局的變量替換
wordMLPackage.getMainDocumentPart().variableReplace(mappings);
String out = dir + "/out.docx";
Docx4J.save(wordMLPackage, new File(out));
}
}
輸出如下
image.png
word文檔格式復(fù)雜宙址,使用以上方式替換文本需特別注意,使用時(shí)建議做測(cè)試