按照模板下载word

该博客介绍了如何利用Freemarker模板引擎将XML格式的Word文档转换为动态模板,并在Java后端通过Controller接口实现动态参数填充,生成定制化的Word文档。涉及的关键步骤包括创建FTL模板、配置Freemarker、参数处理以及工具类的编写和使用。
摘要由CSDN通过智能技术生成

word模板编辑,参数名用${}包裹

建议先把整个${}…写在txt中再copy进来,不然可能格式错误

在这里插入图片描述

将word另存为xml

用Notepad2打开xml,Ctrl+F 搜索$, 检查变量和符号是否正常,变量后面可以都加上?if_exists用于判空。

如:${deptName?if_exists}

然后将.xml的后缀名改成ftl,即ftl模板,将模板放到项目中去

pom导入依赖,各个项目的freemarker依赖版本不一样

<!-- 导入为word(start) -->
        <!--添加freeMarker-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
<!--            <version>2.3.30</version>-->
        </dependency>
        <!-- 导入为word(end) -->

Controller 接口

/**
 * 导出wordd文档
 */
@GetMapping(value="/downloadWord/{orderGenerateId}")
public AjaxResult ExportWord(@PathVariable Long orderGenerateId) throws IOException {
	//用于接收写入你定义的模板里的参数
    Map dataMap = new HashMap();
    //写入参数
    dataMap = powerOrderGenerateService.export(orderGenerateId);
    //生成文件,将文件名返回
    String name = WordUtil.createDoc(dataMap,"order.ftl");
    //下载的文件地址固定在一个地方,前端调用下载后删除就可以
    AjaxResult json = AjaxResult.success(name);
    return json;
}

参数写入方法

Map<String,Object> params = new HashMap<>();
params.put("模板中的参数名",对应的数据);

将参数传入生成文件的方法中

//dataMap参数map 后边的是你对应的模板名称
//模板放到resources下templates文件夹里面
String name = WordUtil.createDoc(dataMap,"order.ftl");

工具类

package com.ruoyi.utils;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Component;

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

@Component
public class WordUtil {

	//resources下,模板放哪,就是哪个文件夹名
	//模板路径
    private static final String FTL_FP = "/templates/"; 

    private static Configuration configuration = null;
    static{
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");//设置默认的编码
    }

    /**
     *
     * @param dataMap 数据库数据
     * @param ftl  替换的模板
     * @return
     * @throws IOException
     */
    public static String createDoc(Map dataMap, String ftl) throws IOException {

        // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
        // ftl文件存放路径
        //configuration.setClassForTemplateLoading(,FTL_FP);
//        TemplateLoader templateLoader = new FileTemplateLoader(new File(FTL_FP));
//        configuration.setDirectoryForTemplateLoading(new File(FTL_FP));
//        TemplateLoader templateLoader = new ClassTemplateLoader(WordUtil.class, FTL_FP);
//        configuration.setTemplateLoader(templateLoader);

        configuration.setClassForTemplateLoading(WordUtil.class,FTL_FP);
        Template t = null;
        try {
            // test.ftl为要装载的模板
            t = configuration.getTemplate(ftl);
            t.setEncoding("utf-8");

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 输出文档路径及名称
        String file_name= "发电订单"+ DateUtils.getNowDate().getTime()+".doc";
        //RuoYiConfig.getDownloadPath() 下载后的文件放置路径
        File outFile = new File(RuoYiConfig.getDownloadPath()+file_name);
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
        } catch (Exception e1) {
            e1.printStackTrace();
            file_name = "";
        }
        try {
            t.process(dataMap, out);
            out.close();
        } catch (TemplateException e2) {
            e2.printStackTrace();
            file_name = "";
        } catch (IOException e) {
            e.printStackTrace();
            file_name = "";
        }
        return file_name;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值