SpringBoot导出Word文档的三种方式
一、导出方案
-
1、直接在Java代码里创建Word文档,设置格式样式等,然后导出。(略)
-
2、富文本转换后的HTML下载为Word文档。相当于把HTML转为Word导出
-
3、使用模板技术导出。固定格式、可以写入不同数据
其他:
- springboot版本:2.7.11
- 导出”页面视图“参考:https://my.oschina.net/u/1045509/blog/1924024
- xml格式化:https://tool.ip138.com/xml/
- HTTP下载 常用的需要设置的MIME类型
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12
.mdb application/vnd.ms-access
二、富文本转换后的HTML下载为Word文档
1、准备
-
业务需求
- 前端使用富文本插件生成带HTML标签的word文档,然后需要下载这个word文档。
- 每个word文档的格式是可变的
-
扩展业务需求:
- 甚至可以去替换HTML的Word中的内容,然后导出需要的文档;缺点:替换字符串麻烦、而且HTML的Word的标签还需要研究。
- 基于上述的业务需求。建议使用模板技术导出(也就是“三”)
-
参考:
-
导出结果
2、实现
2.1、导包
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
2.2、HTML的word文档
package com.cc.ewd.html;
/**
* @author CC
* @since 2023/4/24 0024
*/
public interface HtmlConstants {
/**
* 普通文档(富文本生成的)
*/
String HTML1 = "<h1 style=\"text-align: center;\"><strong>文章标题</strong></h1><h1><strong>一、标题1" +
"</strong></h1><p><strong> 我是数据:{NUM}</strong></p><h2><strong>" +
"1.1、吾问无为谓</strong></h2><table style=\"width: 100%;\">" +
"<tbody><tr><th colSpan=\"1\" rowSpan=\"1\" width=\"auto\">序号</th>" +
"<th colSpan=\"1