Freemaker dynamic export-based word template

Learning from: https://www.cnblogs.com/lsy-blogs/p/9243281.html

A, jar package used:

 

Second, the basic idea of ​​dynamic export of Word templates:

1, first created by his own word to be exported in the form of the word + text template, template, fill in where needed to fill in the contents of $ {} braces for the background passed in the parameter name, then save it as a template xml format;

2, xml format files make the appropriate changes:

(1)} {$ modified location is located, so $ {} in a tag, since the replacement value is identified according} {$, $ {} must make in a tag:

 

(2) if required cycle output, you need to add <#list> </> tag, similar to the enhanced for loop, whether or text form as long as the required cycle output, as long as the cycle of the output data to find a good label, then use <#list> </> expansion live, then modify the corresponding parameter name $ {} to loop the output data:

 

Third, using the word template freemaker achieve dynamic export basic steps:

1, the project introduced freemaker engine jar package:

 

2, the word freemaker export of tools into the project, and modify the path and name of the corresponding word of xml template located:

 

3, write code, to obtain the corresponding data word in need, ultimately stored in a map to (name of the parameter must correspond with the word xml template parameter name remains the same):

 

 

4, in preparing the general method, the results of the map data is transmitted to the tool class methods, to achieve word derived;

 

5, through the above steps, can be changed dynamically derive the word.

Fourth, the need to pay attention:

1, word templates in xml} {$ a must be in the same label;

2, if there is data to be output from the cycle, each piece of data in the background must be placed in an object, not on a map, the data output cycle in the background is a list stored in the corresponding set;

3, backstage pass parameters to the word template can only pass a parameter map, so whether it is a single parameter list or collection of objects, eventually integrated in a map stored in;

4、后台传递给word模板中的参数,不要为null,如果是不存在的值,那么就传递空字符串,也不要传递null进来。

五、word导出工具类代码如下:

复制代码
package com.jeecg.util;

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

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class WordUtils { // 配置信息,代码本身写的还是很可读的,就不过多注解了
    private static Configuration configuration = null;
    // 这里注意的是利用WordUtils的类加载器动态获得模板文件的位置
    private static final String templateFolder = WordUtils.class.getClassLoader().getResource("../../").getPath()
            + "export/template/";
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private WordUtils() {
        throw new AssertionError();
    }

    public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,String fileName)
            throws IOException {
        Template freemarkerTemplate = configuration.getTemplate("TMCatalogMainTemplateBatchDown.xml");
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map, freemarkerTemplate);
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            fileName = fileName+".doc";
            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;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if (fin != null)
                fin.close();
            if (out != null)
                out.close();
            if (file != null)
                file.delete(); // 删除临时文件
        }
    }

    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name = "test.doc";
        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;
    }
}
复制代码

 六、导出多个word的压缩包,思路详情和代码见连接:

https://www.cnblogs.com/lsy-blogs/p/10173904.html

Guess you like

Origin www.cnblogs.com/Bkxk/p/12181575.html