Export Word

Code:

package com.wangtiansoft.stla.provider.utils;

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

import java.io.*;
import java.util.*;

public class WordUtil {

    /**
     * 生成word文件
     * @param dataMap word中需要展示数据
     * @param templateName word模板名称,例如:1.ftl
     * @param filePath 文件生成的目标路径,例如:D:/doc/
     * @param fileName 生成的文件名称,例如:test.doc
     */
    public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
        try {
            //创建配置实例
            Configuration configuration = new Configuration();
            //设置编码
            configuration.setDefaultEncoding("UTF-8");
            //ftl模板文件
            configuration.setClassForTemplateLoading(WordUtil.class,"/");
            //获取模板
            Template template = configuration.getTemplate(templateName,"UTF-8");
            //输出文件
            File outFile = new File(filePath+File.separator+fileName);
            //如果输出目标文件夹不存在,则创建
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }
            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
            //生成文件
            template.process(dataMap, out);
            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<Object> datas = new ArrayList<>();
        dataMap.put("date1","2020.3.9");
        dataMap.put("date2","2020.3.10");
        dataMap.put("fileName","fileName");
        //文件路径
        String filePath = "D:/doc/";
        //文件名称
        String fileOnlyName = "文档.doc";
        //生成word  数据包装,模板名,文件生成路径,生成的文件名
        WordUtil.createWord(dataMap, "1.ftl", filePath, fileOnlyName);
    }
}

Specific instructions:
1.ftl is the word template, content:
Insert picture description here
ftl production steps:

  1. The dynamic data that needs to be replaced in the word template is occupied by the $ {} placeholder. Each field of the placeholder is the field you need to put in the map
  2. Save word as xml format
    Insert picture description here
  3. Then use the software that can edit the xml to open it. I opened it directly with the idea. Some of them are in the wrong format. For example:
    Insert picture description here
    directly delete the line marked with red in front of {data2} , Protect certificate Yes , The guarantee is: {}such DATA2 format, all modifications
  4. Then change the file suffix to ftl
  5. You can run the main method and it ’s ok
Published 104 original articles · won 18 · views 8604

Guess you like

Origin blog.csdn.net/y368769/article/details/104776312