一,创建word模板
1.新建一个word文档
2.分别给四个参数设置域
(1)将鼠标置于想要设置域的地方
(2)设置域名
(3)设置好之后如下图所示
二,项目
1,引入maven依赖
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>18.5</version> <classifier>jdk16</classifier> </dependency>
2,加载授权文件
public static boolean getLicense() { boolean result = false; try { InputStream is = AsposeToWordTest.class.getClassLoader().getResourceAsStream("license-word.xml"); License aposeLic = new License(); aposeLic.setLicense(is); result = true; } catch (Exception e) { e.printStackTrace(); } return result; }
3,获取值以及插入到模板中并生成新的文档
public static void main(String[] args) throws Exception { // 验证License if (!getLicense()) { return; } //模板word String template = "E:\test\temp.docx"; //目标word String destdoc = "E:\test\edit.docx"; //定义文档接口 Document doc = new Document(template); //文本域 String[] Flds = new String[]{"caseIssue","policeName", "caseName", "caseTime"}; String caseIssue = "001"; String policeName = "XX派出所"; String caseName = "0727电动车盗窃案"; String caseTime = "2018-07-26 12:20:22"; //值 Object[] Vals = new Object[]{caseIssue,policeName, caseName, caseTime}; //调用接口 doc.getMailMerge().execute(Flds, Vals); doc.save(destdoc); System.out.println("完成"); }
4,结果
其中设置域的图片引用于http://www.xiaoguo123.com/p/aspose_words_java_template/