Java操作word进行动态数据绑定

168 阅读1分钟

1、创建模板

新建一个docx结尾的word文档进行将要生成文档的撰写,其中需要动态绑定的部分使用{{var}},其他部分正常书写。

2、 引入依赖

   <dependency>
       <groupId>cn.afterturn</groupId>
       <artifactId>easypoi-base</artifactId>
       <version>4.3.0</version>
   </dependency>
   <dependency>
       <groupId>cn.afterturn</groupId>
       <artifactId>easypoi-web</artifactId>
       <version>4.3.0</version>
   </dependency>
   <dependency>
       <groupId>cn.afterturn</groupId>
       <artifactId>easypoi-annotation</artifactId>
       <version>4.3.0</version>
   </dependency>

3、编写代码

import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
​
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
​
/**
 * word动态取值生成
 */
public class WordTest {
    public static void main(String[] args) throws Exception {
        Map<String,Object> map = new HashMap();
        map.put("name","张三");
        map.put("sex","男");
        map.put("age","20");
        map.put("mz","汉");
        //模板路径
        XWPFDocument xwpfDocument = WordExportUtil.exportWord07("E:/Test/test01.docx",map);
        //生成路径
        OutputStream fileOutputStream = new FileOutputStream("E:\Test\test02.docx");
        xwpfDocument.write(fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        System.out.println("work is done");
    }
}