1.首先创建word模板文件aaa.docx

需要填充的字段用如下方式表示

2.导入依赖

<dependency>
   <groupId>com.deepoove</groupId>
   <artifactId>poi-tl</artifactId>
   <version>1.5.1</version>
</dependency>

3.填充方法

package com.example.demo;

import com.deepoove.poi.XWPFTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PortWorld {
    public static void main(String[] args) throws IOException {
        //1.数据,如果查询出来的是对象,可以转成map
        Map<String, String> map = new HashMap<>();
        map.put("name","张三");
        map.put("age","25");
        String uploadPath = "E:/FileData/";
        String template = "pdf/template/aaa.docx";
        String expotr = "pdf/template/" + String.format("tmp%d/title.docx", System.currentTimeMillis());
        String templateUrl = uploadPath + template;
        String exportUrl = uploadPath + expotr;
        //2.填充数据并生成新的word保存到exportUrl路劲下
        addDataToWorld(map,templateUrl,exportUrl);
    }

    public static File addDataToWorld(Map map,String templateUrl,String exportUrl) throws IOException {
        XWPFTemplate template = XWPFTemplate.compile(templateUrl).render(map);
        File file = new File(exportUrl);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream out = new FileOutputStream(file);
        template.write(out);
        out.flush();
        out.close();
        template.close();
        return file;
    }
}

4.对象转map

package io.renren.common.utils;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class ObjectToMap {
    public static Map<String, String> convertToMap(Object obj) {
        try {
            if (obj instanceof Map) {
                return (Map)obj;
            }
            Map<String, String> returnMap = BeanUtils.describe(obj);
            returnMap.remove("class");
            return returnMap;
        } catch (IllegalAccessException e1) {
            e1.getMessage();
        } catch (InvocationTargetException e2) {
            e2.getMessage();
        } catch (NoSuchMethodException e3) {
            e3.getMessage();
        }
        return new HashMap();
    }
}

 

 

 

 

 

 

更多推荐