欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用freemarker生成word模板导出

程序员文章站 2022-04-30 09:25:52
...

1导入jar包

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

2模板生成

  • 1、新建word

使用freemarker生成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展示

使用freemarker生成word模板导出