POI
freemarker处理多图片插入到doc文档
文章目录
- POI
 - 前言
 - 一、doc模板转换成xml文件格式?
 - 二、修改xml文件并转为ftl文件
 - 1.集合内容
 - 2.xml修改集合处理
 - (1)头部加入图片的循环
 - (2)需要循环的数据集合处理
 - (3)加入图片base64
 
- 3.把文件名直接改成ftl就行
 
- 三、代码处理
 - 1.controller层
 - 2.service
 - 3.util
 
- 总结
 
前言
freemarker导出doc文档需要在多个table里面插入相关图片。
一、doc模板转换成xml文件格式?
这边我使用的是WPS


完成后的xml具体内容
二、修改xml文件并转为ftl文件
1.集合内容

2.xml修改集合处理
(1)头部加入图片的循环

(2)需要循环的数据集合处理

(3)加入图片base64

 这三点是图片能循环出来比较关键的点!!
3.把文件名直接改成ftl就行
放入以下路径
 
三、代码处理
1.controller层
    @PostMapping("/download")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "下载doc文档")
    public void download(HttpServletResponse response) {
        exportService.download(response);
    }
 
2.service
    @Override
    public void download(HttpServletResponse response) {
		Map<String, Object> data = getPublicityData();
        try {
            Template template = WordUtils.getTemplate(this, "/templates/ftl", "公告.ftl");
            WordUtils.exportMillCertificateWord(template,response, data, "公告");
        }catch (Exception e) {
            throw new ServiceException("模板导出失败!");
        }
    }
    private Map<String, Object> getPublicityData() {
        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> exportList = new ArrayList<>();
        String relationship = "rId";
        int relationship_id = 9;
        int sortNum = 0;
        //数据进行封装成 dataList对象数据---以下封装数据只是用来测试,你们需要自己替换成真实数据
        for (int i=0; i<2; i++) {
            sortNum++;
            //huTool数字转大写
            String numberChinese = NumberChineseFormatter.format(sortNum, false);
            Map<String, Object> export = new HashMap<>();
            //添加 detail.post [边路射手、中路法师]等
            export.put("post", numberChinese + "、边路射手");
            List<Map<String, String>> staffList = new ArrayList<>();
            //处理staff内容
            for (int j=0; j<2; j++) {
                Map<String, String> staff = new HashMap<>();
                staff.put("info", "孙尚香,女,三国吴郡富春(今浙江富阳)人,丈夫刘备");
                staff.put("photo", getImageStr("图片的网络地址例如:https://123.jpg"));
                staff.put("name", j+".jpg");
                relationship_id++;
                staff.put("relationship_id", relationship+relationship_id);
                staffList.add(staff);
            }
            export.put("staffList", staffList);
            exportList.add(export);
        }
        data.put("dataList", exportList);
        return data;
    }
	//获取图片base64
	public static String getImageStr(String imgFile) {
        if (Func.isEmpty(imgFile)) return "";
        InputStream in = null;
        byte[] data = null;
        try {
            if(imgFile.startsWith("http")){          //获取在线图片
                URL url = new URL(imgFile);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5 * 1000);
                in = conn.getInputStream();
            }else{      //获取线下图片
                in = new FileInputStream(imgFile);
            }
        
            int c;
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            while((c = in.read()) >= 0){
                buff.write(c);
            }
            data = buff.toByteArray();
            buff.close();
            in.read(data);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        if(data!=null && data.length>0){
            return encoder.encode(data);
        }
        return null;
    }
 
3.util
package org.ss.common.utils;
import cn.hutool.core.util.ZipUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.ss.core.log.exception.ServiceException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
public class WordUtils {
    private WordUtils() {
        throw new AssertionError();
    }
    public static Template getTemplate(Object obj ,String url, String path) {
        Configuration configuration = new Configuration();
        //设置编码
        configuration.setDefaultEncoding("utf-8");
        // 例如/templates/ftl
        configuration.setClassForTemplateLoading(obj.getClass(), url);
        Template template;
        try {
            //例如 ss.ftl
            template = configuration.getTemplate(path);
        }catch (Exception e){
            throw new ServiceException("获取模板失败!");
        }
        return template;
    }
    public static void exportMillCertificateWord(Template freemarkerTemplate,HttpServletResponse response, Map map, String title) throws IOException {
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            String fileName = title+".doc";
            file = createDoc(fileName,map,freemarkerTemplate);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int bytesToRead = -1;
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if(fin != null) {
                fin.close();
                fin = null;
            }
            if(out != null) {
                out.close();
                out = null;
            }
            if(file != null) {
                file.delete();
                file = null;
            }
        }
    }
    private static File createDoc(String name, Map<?, ?> dataMap, Template template) {
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}
 
总结
respect
以上就是今天的内容


















