SpringBoot導出Word文檔的三種方式 一、導出方案 1、直接在Java代碼里創建Word文檔,設置格式樣式等,然後導出。(略) 需要的見:https://blog.csdn.net/qq_42682745/article/details/120867432 2、富文本轉換後的HTML下載為 ...
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\" rowSpan=\"1\" width=\"auto\">第一列</th>" +
"<th colSpan=\"1\" rowSpan=\"1\" width=\"auto\">第二列</th>" +
"<th colSpan=\"1\" rowSpan=\"1\" width=\"auto\">第三列</th>" +
"<th colSpan=\"1\" rowSpan=\"1\" width=\"auto\">第四列</th>" +
"</tr><tr><td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">1</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">11</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">22</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">33</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">44</td>" +
"</tr><tr><td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">2</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">11</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">22</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">33</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">44</td>" +
"</tr><tr><td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">3</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">11</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">22</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">33</td>" +
"<td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">44</td></tr>" +
"</tbody></table><p><br></p>";
/**
* 帶表格文檔(可以富文本生成,也可以使用word文檔另存為HTML文件,然後拷出來)
*/
String HTML2 = "<!--StartFragment--><div class=\"Section0\" style=\"layout-grid:15.6000pt;\" ><h1 align=center style=\"text-align:center;\" ><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;\n" +
"font-size:22.0000pt;mso-font-kerning:22.0000pt;\" ><font face=\"宋體\" >標題</font></span></b><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;\n" +
"font-size:22.0000pt;mso-font-kerning:22.0000pt;\" ><o:p></o:p></span></b></h1><h2><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:黑體;mso-ascii-font-family:Arial;\n" +
"mso-hansi-font-family:Arial;mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;\n" +
"font-size:16.0000pt;mso-font-kerning:1.0000pt;\" ><font face=\"黑體\" >一、段落</font><font face=\"Arial\" >1</font></span></b><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:Arial;mso-fareast-font-family:黑體;\n" +
"mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;font-size:16.0000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></b></h2><p class=MsoNormal ><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><font face=\"宋體\" >噠噠</font></span><b><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';color:rgb(0,0,255);\n" +
"font-weight:bold;font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"宋體\" >噠噠噠</font></span></b><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><font face=\"宋體\" >噠</font></span><span style=\"mso-spacerun:'yes';font-family:Calibri;mso-fareast-font-family:宋體;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p><h3><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;\n" +
"font-size:16.0000pt;mso-font-kerning:1.0000pt;\" ><font face=\"Calibri\" >1.1</font><font face=\"宋體\" >、表格</font></span></b><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:Calibri;mso-fareast-font-family:宋體;\n" +
"mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;font-size:16.0000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></b></h3><table class=MsoTableGrid border=1 cellspacing=0 style=\"border-collapse:collapse;border:none;mso-border-left-alt:0.5000pt solid windowtext;\n" +
"mso-border-top-alt:0.5000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;mso-border-bottom-alt:0.5000pt solid windowtext;\n" +
"mso-border-insideh:0.5000pt solid windowtext;mso-border-insidev:0.5000pt solid windowtext;mso-padding-alt:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;\" ><tr><td width=142 valign=center style=\"width:106.5000pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:1.0000pt solid windowtext;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"宋體\" >序號</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td><td width=142 valign=center style=\"width:106.5000pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:1.0000pt solid windowtext;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"宋體\" >列</font><font face=\"Calibri\" >1</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td><td width=142 valign=center style=\"width:106.5500pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:1.0000pt solid windowtext;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"宋體\" >列</font><font face=\"Calibri\" >2</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td><td width=142 valign=center style=\"width:106.5500pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:1.0000pt solid windowtext;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"宋體\" >列</font><font face=\"Calibri\" >3</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td></tr><tr><td width=142 valign=center style=\"width:106.5000pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:none;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"Calibri\" >1</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td><td width=142 valign=center style=\"width:106.5000pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:none;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"Calibri\" >11</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td><td width=142 valign=center style=\"width:106.5500pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:none;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"Calibri\" >22</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td><td width=142 valign=center style=\"width:106.5500pt;padding:0.0000pt 5.4000pt 0.0000pt 5.4000pt ;border-left:1.0000pt solid windowtext;\n" +
"mso-border-left-alt:0.5000pt solid windowtext;border-right:1.0000pt solid windowtext;mso-border-right-alt:0.5000pt solid windowtext;\n" +
"border-top:none;mso-border-top-alt:0.5000pt solid windowtext;border-bottom:1.0000pt solid windowtext;\n" +
"mso-border-bottom-alt:0.5000pt solid windowtext;\" ><p class=MsoNormal align=center style=\"text-align:center;\" ><span style=\"font-family:宋體;mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><font face=\"Calibri\" >33</font></span><span style=\"font-family:Calibri;mso-fareast-font-family:宋體;mso-bidi-font-family:'Times New Roman';\n" +
"font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></p></td></tr></table><p class=MsoNormal ><span style=\"mso-spacerun:'yes';font-family:Calibri;mso-fareast-font-family:宋體;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p> </o:p></span></p><p class=MsoNormal ><span style=\"mso-spacerun:'yes';font-family:Calibri;mso-fareast-font-family:宋體;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p> </o:p></span></p><p class=MsoNormal ><span style=\"mso-spacerun:'yes';font-family:Calibri;mso-fareast-font-family:宋體;\n" +
"mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;mso-font-kerning:1.0000pt;\" ><o:p> </o:p></span></p><h2><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:黑體;mso-ascii-font-family:Arial;\n" +
"mso-hansi-font-family:Arial;mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;\n" +
"font-size:16.0000pt;mso-font-kerning:1.0000pt;\" ><font face=\"黑體\" >二、段落</font><font face=\"Arial\" >2</font></span></b><b style=\"mso-bidi-font-weight:normal\" ><span style=\"mso-spacerun:'yes';font-family:Arial;mso-fareast-font-family:黑體;\n" +
"mso-bidi-font-family:'Times New Roman';mso-ansi-font-weight:bold;font-size:16.0000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><o:p></o:p></span></b></h2><p class=MsoNormal ><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><o:p> </o:p></span></p><p class=MsoNormal ><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><o:p> </o:p></span></p><p class=MsoNormal ><span style=\"mso-spacerun:'yes';font-family:宋體;mso-ascii-font-family:Calibri;\n" +
"mso-hansi-font-family:Calibri;mso-bidi-font-family:'Times New Roman';font-size:10.5000pt;\n" +
"mso-font-kerning:1.0000pt;\" ><o:p> </o:p></span></p></div><!--EndFragment-->";
}
2.3、導出
-
邏輯、註意事項看註釋
-
代碼:
package com.cc.ewd.web.controller;
import com.cc.ewd.html.HtmlConstants;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/** 業務需求:前端使用富文本插件生成帶HTML標簽的word文檔,然後需要下載這個word文檔。
* @author CC
* @since 2023/4/24 0024
*/
@RestController
@RequestMapping("/apachePoiExport")
public class ApachePoiExport {
/** 將HTML內容(富文本生成的HTML)轉換為Word文檔並下載
* @param response HTTP響應
*/
@GetMapping
public void getDoc(HttpServletResponse response) {
String fileName = "Word文件名";
String html = HtmlConstants.HTML2;
//導出word的方法
exportWord(fileName, html, response);
}
/** <p>將HTML內容(富文本生成的HTML)轉換為Word文檔並下載(word2007之後的_docx)</p>
* <li>參考:https://my.oschina.net/u/1045509/blog/1924024</li>
* <li>參考:https://blog.csdn.net/qq_42682745/article/details/120867432</li>
* @param fileName 文件名
* @param html 富文本生成的HTML
* @param response 響應
* @since 2023/4/25 0025
* @author CC
**/
public static void exportWord(String fileName, String html, HttpServletResponse response) {
//0、獲取富文本的html:
// HTML內容必須被<html><body></body></html>包裝;最好設置一下編碼格式
// HTML在這裡設置<head></head>是為了讓輸入的文檔是以"頁面視圖"。而不是"Web版式"
String wrappedHtml =
"<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n" +
"xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"\n" +
"xmlns=\"http://www.w3.org/TR/REC-html40\">" +
"<head>" +
"<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves>" +
"<w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>" +
"<w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>" +
"<w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian>" +
"<w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/>" +
"<w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/>" +
"<w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/>" +
"<w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel>" +
"<m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/>" +
"<m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/>" +
"<m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument>" +
"</xml><![endif]-->" +
"</head>" +
"<body>%s</body>" +
"</html>";
wrappedHtml = String.format(wrappedHtml, html);
//1、將HTML轉換為Word文檔byte數組
byte[] bytes = wrappedHtml.getBytes(StandardCharsets.UTF_8);
try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
InputStream byteInputStream = new ByteArrayInputStream(bytes);
// InputStream inputStream = new BufferedInputStream(byteInputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
){
//2、使用ApachePoi轉換word並設置到輸出流outputStream
DirectoryEntry directory = poifsFileSystem.getRoot();
//WordDocument名稱不允許修改
directory.createDocument("WordDocument", byteInputStream);
//將Word文檔寫入POIFSFileSystem對象
poifsFileSystem.writeFilesystem(outputStream);
//3、①將Word文檔(輸出流outputStream)寫入HTTP響應並下載;②也可以上傳到自己的文件伺服器然後返回URL給前端下載。
response.setCharacterEncoding("utf-8");
//設置content-type就是告訴瀏覽器這是啥玩意兒
//"octet-stream" :通用二進位流;
//"msword" :Microsoft Word文檔
//"vnd.openxmlformats-officedocument.wordprocessingml.document" :響應的內容類型設置為Microsoft Word 2007及更高版本的docx格式。對應的文件名尾碼需要改成”docx“
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
//解決跨域不顯示在header裡面的問題
response.setHeader("Access-Control-Expose-Headers","Content-disposition");
//"attachment":讓瀏覽器把響應視為附件並下載
//"inline": 讓瀏覽器打開Word文檔而不是下載它
response.setHeader("Content-disposition","attachment; filename=" +
URLEncoder.encode(fileName.concat(".docx"), "UTF-8"));
//BufferedOutputStream緩衝流:可以將數據緩存在記憶體中,以減少對底層IO的調用次數,從而提高性能。
//ServletOutputStream:用於向客戶端發送數據的
//因為需要將數據寫入HTTP響應,所以使用ServletOutputStream是更好的選擇。
OutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(outputStream.toByteArray());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、使用模板技術導出
-
使用Thymeleaf模板技術(推薦,也是我使用的)。也可以使用FreeMarker
-
Word文件的格式是固定
-
可以根據需求寫入不同的數據
1、準備工作
1.1、導包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1.2、導出文件的預處理,Thymeleaf語法
- 使用WPS(建議使用微軟的Word)新建一個需要導出Word文件
- 這個Word文件中,需要替換的值,最好使用單獨的格式。因為單獨的格式在HTML或者xml中才能區分
- 弄好Word文件,最後另存為xml格式或者HTML(單個文件)格式。就得到我們需要的xml或者HTML格式的Word文件。
-
使用Thymeleaf語法修改xml文件
-
參考:Thymeleaf更多語法見下麵:
https://blog.csdn.net/weixin_45203607/article/details/120251923 https://blog.csdn.net/guoqigengxin/article/details/108674177普通文本
-
普通文本
-
- 迴圈
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- 條件判斷:if-else
1.3、把處理好的xml文件放到resources下
1.4、使用HTML的註意事項
-
見附件:thymeleaf_3_wps.html
-
另存為後,修改HTML的編碼格式:utf-8
- 設置值,直接可以設置在:font 標簽上
- “頁面視圖“修改:
- 參考導出頁面視圖見:一、導出方案
2、原理
- 可以使用xml導出、也可以使用HTML導出。
- 導出前需要預處理xml
- 可以使用下麵的進行測試、導出。
2.1、原理
package com.cc.ewd.web.controller;
import com.cc.ewd.vo.Msg4Vo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** thymeleaf導出的原理
* @author CC
* @since 2023/4/25 0025
*/
@RestController
@RequestMapping("/thymeleafTheoryExport")
public class ThymeleafTheoryExport {
@Resource
private SpringTemplateEngine springTemplateEngine;
/** <p>原理</p>
* <ol>
* <li>相當於把word文件轉為xml或者html,然後修改其中的值再以xml、html下載成word文件</li>
* <li>這個方法只能運行一次,因為對ClassLoaderTemplateResolver的設置是一次性的</li>
* <li>所以需要將ClassLoaderTemplateResolver設置成單例:配置Bean。</li>
* <li>doc或docx的模板別使用WPS的文檔,使用微軟的office新建word文檔,然後轉為xml或html</li>
* <li>可以導出xml、也可以導出html:建議使用xml</li>
* </ol>
*/
@GetMapping
public void thymeleafExport(HttpServletResponse response){
String fileName = "第一個thy的文件";
//一、設置Thymeleaf模板
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
//xml文件地址:自定義xml的文件夾:thymeleafcs/thymeleaf_1_wps.xml
//xml文件地址:預設放在thymeleaf下就可以讀取到
templateResolver.setPrefix("thymeleafcs/");
//設置文件的尾碼
templateResolver.setSuffix(".xml");
// templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("utf-8");
//模板模式:預設是HTML。改為xml
// templateResolver.setTemplateMode(TemplateMode.XML);
templateResolver.setTemplateMode(TemplateMode.HTML);
//載入模板
springTemplateEngine.setTemplateResolver(templateResolver);
//啟用Spring EL編譯器
springTemplateEngine.setEnableSpringELCompiler(true);
//二、設置數據(可以用map,也可以用對象)
Map<String,Object> map = new HashMap<>();
//1普通文本參數
map.put("msg1","我是參數1111");
map.put("msg2","我是參數2222");
map.put("msg3","我是參數3333");
//2if-else參數
map.put("thIf1","1");
map.put("thIf2","2");
//3迴圈:構建集合參數,用於表格:可以是Map;可以是對象
// List<Map<String,Object>> msg4Vos = new ArrayList<>();
List<Msg4Vo> msg4Vos = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//1map方式
// Map<String,Object> map4 = new HashMap<>();
// map4.put("l1","列1-" + i);
// map4.put("l2","列2-" + i);
// map4.put("l3","列3-" + i);
// map4.put("l4","列4-" + i);
// msg4Vos.add(map4);
//2對象方式
Msg4Vo vo = new Msg4Vo();
vo.setL1("列1-" + i);
vo.setL2("列2-" + i);
vo.setL3("列3-" + i);
vo.setL4("列4-" + i);
msg4Vos.add(vo);
}
map.put("msg4Vos",msg4Vos);
//4設置數據
Context context = new Context();
context.setVariables(map);
//寫入輸入(模板名稱,數據)
String process = springTemplateEngine.process("thymeleaf_4_wps_final", context);
//三、下載
//建議下載成doc的。不然微軟的office可能打不開
try {
byte[] bytes = process.getBytes(StandardCharsets.UTF_8);
// ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
// ByteArrayOutputStream outputStream = getByteArrayOutputStream(inputStream);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Access-Control-Expose-Headers","Content-disposition");
response.setHeader("Content-disposition","attachment; filename=" +
URLEncoder.encode(fileName.concat(".doc"), "UTF-8"));
ServletOutputStream out = response.getOutputStream();
//兩種方式都可以:用bytes好些
// out.write(outputStream.toByteArray());
out.write(bytes);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
/** 將 ByteArrayInputStream 拷貝成 ByteArrayOutputStream
* 將 位元組數組輸入流 拷貝成 位元組數組輸出流
*/
public static ByteArrayOutputStream getByteArrayOutputStream(ByteArrayInputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
return outputStream;
}
}
2.2、導出後預覽
3、實現
3.1、yml配置
server:
port: 5555
spring:
#thymeleaf的配置
thymeleaf:
#關閉 Thymeleaf 的緩存開發過程中無需重啟
#Thymeleaf預設會開啟頁面緩存,提高頁面併發能力。但會導致我們修改頁面不會立即被展現,因此我們關閉緩存
cache: false
#設置thymeleaf頁面的編碼
encoding: UTF-8
#模型:XML/HTML5:HTML是預設值, 為了清楚起見, 在此處添加。
mode: XML
#設置thymeleaf頁面的尾碼:.html是預設。
suffix: .xml
#設置thymeleaf頁面的存儲路徑
prefix: classpath:/thymeleafcs/
#使用Spring 4.2.4或更高版本啟用SpringEL編譯器
#可以加快大多數情況下的執行速度, 但是當一個模板中
#的表達式在不同數據類型之間重用時,
#可能與特定情況不相容, 因此該標誌預設為“false”
#以實現更安全的向後相容性。
enable-spring-el-compiler: true
3.2、實現
package com.cc.ewd.web.controller;
import com.cc.ewd.vo.Msg4Vo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** thymeleaf導出的實現
* @author CC
* @since 2023/5/4 0025
*/
@RestController
@RequestMapping("/thymeleafExport")
public class ThymeleafExport {
@Resource
private SpringTemplateEngine springTemplateEngine;
/** <p>原理</p>
* <ol>
* <li>相當於把word文件轉為xml或者html,然後修改其中的值再以xml、html下載成word文件</li>
* <li>這個方法只能運行一次,因為對ClassLoaderTemplateResolver的設置是一次性的</li>
* <li>所以需要將ClassLoaderTemplateResolver設置成單例:配置Bean。</li>
* <li>doc或docx的模板別使用WPS的文檔,使用微軟的office新建word文檔,然後轉為xml或html</li>
* <li>可以導出xml、也可以導出html:建議使用xml</li>
* </ol>
*/
@GetMapping
public void thymeleafExport(HttpServletResponse response){
String fileName = "第二個thy的文件";
//一、設置數據(可以用map,也可以用對象)
Map<String,Object> map = new HashMap<>();
//1普通文本參數
map.put("msg1","我是參數1111");
map.put("msg2","我是參數2222");
map.put("msg3","我是參數3333");
//2if-else參數
map.put("thIf1","1");
map.put("thIf2","2");
//3迴圈:構建集合參數,用於表格:可以是Map;可以是對象
// List<Map<String,Object>> msg4Vos = new ArrayList<>();
List<Msg4Vo> msg4Vos = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//1map方式
// Map<String,Object> map4 = new HashMap<>();
// map4.put("l1","列1-" + i);
// map4.put("l2","列2-" + i);
// map4.put("l3","列3-" + i);
// map4.put("l4","列4-" + i);
// msg4Vos.add(map4);
//2對象方式
Msg4Vo vo = new Msg4Vo();
vo.setL1("列1-" + i);
vo.setL2("列2-" + i);
vo.setL3("列3-" + i);
vo.setL4("列4-" + i);
msg4Vos.add(vo);
}
map.put("msg4Vos",msg4Vos);
//4設置數據
Context context = new Context();
context.setVariables(map);
//寫入輸入(模板名稱,數據)
String process = springTemplateEngine.process("thymeleaf_4_wps_final", context);
//二、下載
//建議下載成doc的。不然微軟的office可能打不開
try {
byte[] bytes = process.getBytes(StandardCharsets.UTF_8);
// ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
// ByteArrayOutputStream outputStream = getByteArrayOutputStream(inputStream);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Access-Control-Expose-Headers","Content-disposition");
response.setHeader("Content-disposition","attachment; filename=" +
URLEncoder.encode(fileName.concat(".doc"), "UTF-8"));
ServletOutputStream out = response.getOutputStream();
//兩種方式都可以:用bytes好些
// out.write(outputStream.toByteArray());
out.write(bytes);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
/** 將 ByteArrayInputStream 拷貝成 ByteArrayOutputStream
* 將 位元組數組輸入流 拷貝成 位元組數組輸出流
*/
public static ByteArrayOutputStream getByteArrayOutputStream(ByteArrayInputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
return outputStream;
}
}
3.3、不使用yml配置,使用配置bean方式
- 可以配置不同的bean,註入使用的時候,使用我們需要的bean。實現動態使用不同類型的模板的功能。
- 如果yml中配置了, 又配置了bean。yml中的配置會失效。
- 其中一個bean一定要添加:@Primary。來設置預設的bean
- config配置
package com.cc.ewd.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;
import javax.annotation.Resource;
/** ThymeLeaf單獨的配置
* @since 2023/5/4 0004
* @author CC
**/
@Configuration
public class MyThymeLeafConfig {
@Resource
private ApplicationContext applicationContext;
/** 自定義的bean
* @return SpringTemplateEngine
* @Primary :<li>作用:指定使用名為“myTemplateEngine”的bean作為預設bean。</li>
* <li>這樣,當您在需要使用SpringTemplateEngine的地方沒有指定@Qualifier註釋時,Spring將使用該預設bean。</li>
* <li>使用@Resource時,可直接設置名字。不用使用@Qualifier註釋</li>
*/
@Bean(name = "myTemplateEngine")
@Primary
public SpringTemplateEngine myTemplateEngine(){
// SpringTemplateEngine自動應用SpringStandardDialect
// 並啟用Spring自己的MessageSource消息解析機制。
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
SpringResourceTemplateResolver templateResolver = myTemplateResolver();
templateEngine.setTemplateResolver(templateResolver);
// 使用Spring 4.2.4或更高版本啟用SpringEL編譯器
// 可以加快大多數情況下的執行速度, 但是當一個模板中
// 的表達式在不同數據類型之間重用時,
// 可能與特定情況不相容, 因此該標誌預設為“false”
// 以實現更安全的向後相容性。
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
/** 自定義配置
* @return SpringResourceTemplateResolver
*/
@Bean("myTemplateResolver")
public SpringResourceTemplateResolver myTemplateResolver(){
// SpringResourceTemplateResolver自動與Spring自己集成
// 資源解決基礎設施, 強烈推薦。
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("classpath:thymeleafcs/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
// HTML是預設值, 為了清楚起見, 在此處添加。
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
//----------------------------------------------
/** 自定義的bean2
* @return SpringTemplateEngine
*/
@Bean(name = "myTemplateEngine2")
public SpringTemplateEngine myTemplateEngine2(){
// SpringTemplateEngine自動應用SpringStandardDialect
// 並啟用Spring自己的MessageSource消息解析機制。
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
SpringResourceTemplateResolver templateResolver = myTemplateResolver2();
templateEngine.setTemplateResolver(templateResolver);
// 使用Spring 4.2.4或更高版本啟用SpringEL編譯器
// 可以加快大多數情況下的執行速度, 但是當一個模板中
// 的表達式在不同數據類型之間重用時,
// 可能與特定情況不相容, 因此該標誌預設為“false”
// 以實現更安全的向後相容性。
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
/** 自定義配置2
* @return SpringResourceTemplateResolver
*/
@Bean("myTemplateResolver2")
public SpringResourceTemplateResolver myTemplateResolver2(){
// SpringResourceTemplateResolver自動與Spring自己集成
// 資源解決基礎設施, 強烈推薦。
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("classpath:thymeleafcs/");
templateResolver.setSuffix(".xml");
templateResolver.setCharacterEncoding("UTF-8");
// HTML是預設值, 為了清楚起見, 在此處添加。
templateResolver.setTemplateMode(TemplateMode.XML);
return templateResolver;
}
}
-
使用
-
@Resource註入:
@Resource(name = "myTemplateEngine") private SpringTemplateEngine springTemplateEngine;
-
@Autowired註入:
@Autowired @Qualifier("myTemplateEngine") private SpringTemplateEngine springTemplateEngine1Html;
-
配置文件會失效——配置類優先
-
使用:根據傳入的type不同。使用的模板是不同的。
-
package com.cc.ewd.web.controller;
import com.cc.ewd.vo.Msg4Vo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** thymeleaf導出的實現
* @author CC
* @since 2023/5/4 0025
*/
@RestController
@RequestMapping("/thymeleafExport")
public class ThymeleafExport {
// @Resource
// private SpringTemplateEngine springTemplateEngine;
@Resource(name = "myTemplateEngine")
private SpringTemplateEngine springTemplateEngine1Html;
@Resource(name = "myTemplateEngine2")
private SpringTemplateEngine springTemplateEngine2Xml;
/** <p>原理</p>
* <ol>
* <li>相當於把word文件轉為xml或者html,然後修改其中的值再以xml、html下載成word文件</li>
* <li>這個方法只能運行一次,因為對ClassLoaderTemplateResolver的設置是一次性的</li>
* <li>所以需要將ClassLoaderTemplateResolver設置成單例:配置Bean。</li>
* <li>doc或docx的模板別使用WPS的文檔,使用微軟的office新建word文檔,然後轉為xml或html</li>
* <li>可以導出xml、也可以導出html:建議使用xml</li>
* </ol>
*/
@GetMapping
public void thymeleafExport(@RequestParam String type, HttpServletResponse response){
String fileName = "第二個thy的文件";
//一、設置數據(可以用map,也可以用對象)
Map<String,Object> map = new HashMap<>();
//1普通文本參數
map.put("msg1","我是參數1111");
map.put("msg2","我是參數2222");
map.put("msg3","我是參數3333");
//2if-else參數
map.put("thIf1","1");
map.put("thIf2","2");
//3迴圈:構建集合參數,用於表格:可以是Map;可以是對象
// List<Map<String,Object>> msg4Vos = new ArrayList<>();
List<Msg4Vo> msg4Vos = new ArrayList<>();
for (int i = 0; i < 10; i++) {
//1map方式
// Map<String,Object> map4 = new HashMap<>();
// map4.put("l1","列1-" + i);
// map4.put("l2","列2-" + i);
// map4.put("l3","列3-" + i);
// map4.put("l4","列4-" + i);
// msg4Vos.add(map4);
//2對象方式
Msg4Vo vo = new Msg4Vo();
vo.setL1("列1-" + i);
vo.setL2("列2-" + i);
vo.setL3("列3-" + i);
vo.setL4("列4-" + i);
msg4Vos.add(vo);
}
map.put("msg4Vos",msg4Vos);
//4設置數據
Context context = new Context();
context.setVariables(map);
//寫入輸入(模板名稱,數據):1:html;2:xml
String process = "";
if ("1".equals(type)){
process = springTemplateEngine1Html.process("thymeleaf_3_wps", context);
}else if ("2".equals(type)){
process = springTemplateEngine2Xml.process("thymeleaf_4_wps_final", context);
}
//二、下載
//建議下載成doc的。不然微軟的office可能打不開
try {
byte[] bytes = process.getBytes(StandardCharsets.UTF_8);
// ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
// ByteArrayOutputStream outputStream = getByteArrayOutputStream(inputStream);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Access-Control-Expose-Headers","Content-disposition");
response.setHeader("Content-disposition","attachment; filename=" +
URLEncoder.encode(fileName.concat(".doc"), "UTF-8"));
ServletOutputStream out = response.getOutputStream();
//兩種方式都可以:用bytes好些
// out.write(outputStream.toByteArray());
out.write(bytes);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
/** 將 ByteArrayInputStream 拷貝成 ByteArrayOutputStream
* 將 位元組數組輸入流 拷貝成 位元組數組輸出流
*/
public static ByteArrayOutputStream getByteArrayOutputStream(ByteArrayInputStream inputStream) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
return outputStream;
}
}
四、總結
- 甚至可以結合Thymeleaf模板技術和ApachePoi技術。
- 先使用Thymeleaf模板技術替換Word文檔中的值。然後得到完整的HTML格式的Word文檔
- 然後使用ApachePoi導出HTML格式的Word文檔
- 文中使用到的文檔: