使用freemarker生成word模板导出

1导入jar包

        <!--生成word使用-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>

2模板生成

  • 1、新建word

在这里插入图片描述
需要注意的是把你后期想插入的值用${}代替,完事要另存为XML格式文档

  • 2、把xml格式文件后缀改为ftl,并把ftl文件加入代码里资源文件夹下

注意:如果需要加入图片的话,在文档里复制一个图片,然后在ftl文件里找到图片对应的编码,删除掉,用${imgStr}替代

3代码

  • 1工具类代码
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 导出WORD工具类
 *
 * @author
 * @时间 2014-10-9
 */
@Slf4j
public class DocumentUtil {

    private static final String DEFAULT_ENCODING = "utf-8";

    /**
     * 配置信息对象
     */
    private static Configuration configuration;

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_22);

        configuration.setDefaultEncoding(DEFAULT_ENCODING);
        configuration.setClassForTemplateLoading(DocumentUtil.class, "/freeMarkerTemplates");
    }


    /**
     * 获取模板
     *
     * @param name
     * @return
     * @throws Exception
     */
    private static Template getTemplate(String name) throws Exception {
        return configuration.getTemplate(name);
    }

    /**
     * 获取文件
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String getImageStr(InputStream is) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] data = new byte[is.available()];
        is.read(data);
        is.close();
        return encoder.encode(data);
    }

    /**
     * 导出
     *
     * @param temName
     * @param dataMap
     * @param fileName
     * @param response
     * @throws Exception
     */
    public static void exportDoc(String temName, Map dataMap, String fileName, HttpServletResponse response) throws Exception {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        Writer writer = new OutputStreamWriter(response.getOutputStream(), DEFAULT_ENCODING);
        getTemplate(temName).process(dataMap, writer);
    }
}
  • 2生成代码

controller层代码

    /**
     * 导出word
     */
    @GetMapping("/exportWord")
    public void exportPdf(HttpServletResponse response, String id) {
        wordService.exportPdf(response, id);
    }

实现层代码

    @Override
    public void exportPdf(HttpServletResponse response, String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptName", 1);
        map.put("deviceNum", 2);
        map.put("deviceName", 3);
        map.put("deviceModel", 4);
        map.put("factoryNum", 5);
        map.put("manufacturer", 6);
        //插入图片
        map.put("imgStr", Base64.encodeBase64String(图片的二进制byte[]));
        try {
            // 导出
                DocumentUtil.exportDoc("wordExport.ftl", map, "生成的word名称.doc", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

  • 3前端代码
                    this.$http({
                        url: '/admin/deviceInfo/exportPdf',
                        method: 'get',
                        params: Object.assign({
                            id: this.dataForm.id
                        }),
                        responseType: 'blob',
                    }).then(({data}) => {
                        let blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'});
                        if (window.navigator.msSaveOrOpenBlob) {
                            // ie浏览器
                            navigator.msSaveBlob(blob, 'aaa.doc');
                        } else {
                            let link = document.createElement("a");
                            let evt = document.createEvent("HTMLEvents");
                            evt.initEvent("click", false, false);
                            link.download = "aaa.doc";
                            link.style.display = "none";
                            link.href = URL.createObjectURL(blob);
                            document.body.appendChild(link);
                            link.click();
                            window.URL.revokeObjectURL(link.href);
                        }
                        this.visible = false;
                    })

4生成word展示

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值