java导出word文档。Springboot下载.ftl文件到浏览器

本文介绍了如何使用Java后端配合.ftl模板,根据获取的数据动态生成Word文档,包括创建空白文档、转换XML、处理Map数据并插入文档,以及在前端通过HTTPGET请求调用后端接口实现下载。
摘要由CSDN通过智能技术生成

在有些情况,需要导出特定的word文档,文档里面的某些文字是变化的,需要根据获取的数据进行填充,那么使用.ftl文件就很容易实现这个功能。

首先,可以先创建一个空白文档,写一篇范文,保存的格式是*.XML。

创建好之后,可以去网上搜相关的工具,将其转为XML格式代码。这里我是使用的菜鸟工具进行转化的。转换好之后,在项目资源下面创建.ftl文件,然后将格式化的XML代码粘贴上去。

首先选择你保存的word文档,然后再点击复制,复制格式化的XML代码。

创建.ftl文件,将刚才复制的代码粘贴到这个文件里面。

如果你需要动态的往word插入数据,你可以将需要插入数据的地方使用${}替换,这样在生成word文档的时候,会将传进来的map数据一一对应的插入到文档里面。

比如这里,我是动态变化的,假如我传进来的map集合,key为"

firstAuditResponsibleOperator"的value值是"张三",那么我导出的word文档,这个部分值就是"张三".

下面是java后端代码需要的操作,直接上代码。

    @GetMapping("/downloadReport")
    public void downloadReport(HttpServletResponse response){

        //这里map数据根据实际情况而论,这里我做演示,所以就不插入数据
        //如果你要修改word里面的某些文件,就是动态的数据,可以将数据封装成map
        Map map = new HashMap();
        Configuration cfg = new Configuration(Configuration.getVersion());
        cfg.setClassForTemplateLoading(this.getClass(), "/templates/appraisal");
        //生成word
        OutputStream out = null;
        FileInputStream fis = null;
        File file = null;
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/msword");
        try {
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode("下载文档名称.doc", "UTF-8"))));
            //一般情况这里可以不用设置
            //response.addHeader("code", "0");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            Configuration configuration = new Configuration(Configuration.getVersion());
            // 模板存放路径
            configuration.setClassForTemplateLoading(this.getClass(), "/templates/appraisal");
            // 获取模板文件
            Template template = configuration.getTemplate("appraisal.ftl");
            configuration.setDefaultEncoding("UTF-8");
            //往word文档里面插入数据,会将map集合数据插入到文档的对应位置中
            file = createDoc("ccc", map, template);
            fis = new FileInputStream(file);
            out = response.getOutputStream();
            // 缓冲区
            byte[] buffer = new byte[512];
            int bytesToRead = -1;
            // word数据写入并返回
            while ((bytesToRead = fis.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //释放资源
            try {
                if (fis != null) {
                    fis.close();
                }
                out.flush();
                if (out != null) {
                    out.close();
                }
                //删除临时文件
                file.delete();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    //创建临时word文件
    private File createDoc(String fileName, Map map, Template template) {
        File f = new File(fileName);
        try {
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            template.process(map, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return f;
    }

在前端浏览器触发也非常简单。只需简单的一行代码即可。

window.open(这里面放你后端方法的路径)

比如我的方法全路径是127.0.0.1:8080/example/downloadReport,这里就是

window.open('127.0.0.1:8080/example/downloadReport')

导出word文档的流程大致就是这样,都非常简单。 

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
FreeMarker 是一个Java模板引擎,它可以帮助我们根据模板生成各种文件,包括 Word 文档。下面是一个简单的示例,演示如何使用 FreeMarker 创建一个根据 FTL 模板生成 Word 文档的过程: 1. 创建一个 FreeMarker 的配置对象,并设置模板文件所在的目录: ``` Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setDirectoryForTemplateLoading(new File("path/to/ftl/templates")); ``` 2. 从配置对象中获取模板对象: ``` Template template = cfg.getTemplate("template.ftl"); ``` 3. 准备数据模型,可以是一个 JavaBean、Map 或者其他类型的对象: ``` Map<String, Object> data = new HashMap<>(); data.put("title", "Hello, World!"); data.put("content", "This is a test document created by FreeMarker."); ``` 4. 创建一个 Writer 对象,用于输出生成的 Word 文档: ``` Writer out = new FileWriter(new File("path/to/output/doc.docx")); ``` 5. 将数据模型和 Writer 对象传递给模板对象,生成 Word 文档: ``` template.process(data, out); ``` 完整的示例代码如下: ``` import freemarker.template.Configuration; import freemarker.template.Template; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; public class FreeMarkerDemo { public static void main(String[] args) throws Exception { // 创建 Configuration 对象 Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setDirectoryForTemplateLoading(new File("path/to/ftl/templates")); // 获取模板对象 Template template = cfg.getTemplate("template.ftl"); // 准备数据模型 Map<String, Object> data = new HashMap<>(); data.put("title", "Hello, World!"); data.put("content", "This is a test document created by FreeMarker."); // 创建输出流 Writer out = new FileWriter(new File("path/to/output/doc.docx")); // 生成 Word 文档 template.process(data, out); // 关闭输出流 out.close(); } } ``` 注意,上面的示例代码中使用的模板文件FTL 格式,如果要生成 Word 文档,还需要将模板文件转换成 docx 或者其他 Word 文档格式。常见的工具包括 Apache POI 和 Docx4j 等。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值