JAVA uses freemarker template to export Word

1. Import the jar package

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2. Make templates, modify word

First replace the fields that need to be filled in word with ${}

Then change the suffix to ftl

3. Modify the JAVA code

/**
 * @Description
 * @Author yoguo
 * @Date 2020/12/9 14:24
 **/
public class WordUtil {

    public static void export(Map<String,Object> map){
        map.put("modelName","模型名称1");
        map.put("mainCreator","主创人1");
        map.put("mainUnit","主创单位1");
        //模板生成DOC
        String docFile = getTempFile("E://jmds", ContestConstants.SUFFIX_DOCX);
        createDoc(map, "E://jmds/template", ContestConstants.MODEL_JMDS, docFile);
    }

    /**
     * 建立临时文件
     * @param uploadUrl
     * @param suffix
     * @return
     */
    public static String getTempFile(String uploadUrl,String suffix){
        String date = DateUtil.parseDate2SyyyyMMdd(new Date());
        File tempPath = new File(uploadUrl+"/temp/"+date);
        if (!tempPath.exists()){
            tempPath.mkdirs();
        }
        String name = UUID.randomUUID().toString();
        return tempPath+"/"+name+suffix;
    }

    public static void createDoc(Map<String,Object> dataMap,String modelPath,String modelName,String targetFile){
        Writer out = null;
        try {
            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration(new Version("2.3.0"));
            configuration.setDefaultEncoding("utf-8");
            //指定路径的方式,我的路径是
            configuration.setDirectoryForTemplateLoading(new File(modelPath));
            //输出文档路径及名称
            File outFile = new File(targetFile);
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate(modelName, "utf-8");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static void main(String[] args) {
        export(new HashMap<>());
    }
}

 

Guess you like

Origin blog.csdn.net/m0_37574375/article/details/110926275