Java输出Word文档,Java生成Word文档

返回导航页

返回导航页

业务来源

需要将一些信息,生成word然后导出来。

工具推荐

开源的,非常好用,直接跑个demo,你就能体会多方便了!
deepoove

直接安排个demo

操作word和操作excel不太一样,操作word首先需要准备一个模板,需要填充内容的地方,使用占位符,先把位置占好,然后在业务中进行占位符填充!

我解释明白了吗?
不明白?那直接截图官方文档吧!!!
在这里插入图片描述
还不明白?那直接看我写的吧!
安排!
第一步
在这里插入图片描述
第二步
在这里插入图片描述
第三步
多种输出方式,这里代码演示网络流的输出!
在这里插入图片描述

/**获取报告*/
    @RequestMapping("/download/word**/***")
    public void downloadWord(HttpServletResponse response) throws  Exception {
               XWPFTemplate template = XWPFTemplate.compile("src/main/resources/template.docx").render(
                new HashMap<String, Object>(){{
                    put("title", "这个是标题哈,填充进去");
                }});
                // 文件流传输
//        template.writeAndClose(new FileOutputStream("output.docx"));
        // 使用网络流进行传输
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;filename=\""+"输出文件.docx"+"\"");

// HttpServletResponse response
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
     }

postman测试一把咯
在这里插入图片描述
文件名中文的有问题,后续在处理吧!
不过内容没得问题了。
在这里插入图片描述

大坑

################################大坑#########################################

springboot打成jar包,会导致目录结构发生改变,绝对路径是没有用的;
这个问题太坑了,
本地测试都没有问题,上测试环境就出现问题了!!!!
还有就是处理中文乱码问题。

解决方法:
使用流

/**获取报告*/
    @RequestMapping("/download/word**/***")
    public void downloadWord(HttpServletResponse response) throws  Exception {
         ClassPathResource resource = new ClassPathResource("template.docx");
        InputStream inputStream = resource.getInputStream();
        XWPFTemplate template = XWPFTemplate.compile(inputStream).render(
          new HashMap<String, Object>(){{
              put("title", "这个是标题哈,填充进去");
          }});
          // 文件流传输
//        template.writeAndClose(new FileOutputStream("output.docx"));
        // 使用网络流进行传输
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("小可爱文档.docx", "UTF-8"));

// HttpServletResponse response
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
     }
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码头薯条Pro

本文能帮到阁下,在下很开心!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值