Java web 富文本内容生成转为word格式并导出下载

62 篇文章 3 订阅
37 篇文章 2 订阅

Java web 富文本内容生成转为word格式并导出下载

最近思路,按标签逐一解析,实现复杂一点但是完美解决问题:

https://blog.csdn.net/a2272062968/article/details/126227076


思路:Word是完全支持html标签的,但是富文本内容并不是完整的html代码,需要先补全html标签,然后转码输出
问题:虽然导出word doc但是事件内容流还是htm,只不过word帮忙解析展示了,再进行word读取的二次处理就出现问题

依赖包

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.2</version>
</dependency>

上代码

    /**
     * 导出 word 文档
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/download/{id}")
    public Result download(@PathVariable Long id, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String content = "你的富文本内容"
        StringBuilder sbf = new StringBuilder();
        sbf.append("<html><body>");
        sbf.append(content);
        sbf.append("</body></html");
        exportWord(request, response, String.valueOf(sbf), "要导出的文件名");
        return Result.succeed("导出成功");	//Result是我的通用响应返回对象,换成你自己的
    }

    /**
     *
     * @param request
     * @param response
     * @param content  富文本内容
     * @param fileName 导出 word 文件名
     * @throws IOException
     */
    public void exportWord(HttpServletRequest request, HttpServletResponse response, String content, String fileName) throws IOException {
        //这里是必须要设置编码的,不然导出中文就会乱码。
        byte b[] = content.getBytes("utf-8");
        //将字节数组包装到流中
        ByteArrayInputStream bais = new ByteArrayInputStream(b);
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = poifs.getRoot();
        //该步骤不可省略,否则会出现乱码
        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
        //输出文件
        request.setCharacterEncoding("utf-8");
        //导出word格式
        response.setContentType("application/msword");
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "iso8859-1") + ".doc");
        ServletOutputStream ostream = response.getOutputStream();
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
        poifs.close();
    }
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

摘星喵Pro

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值