SpringBoot匯出Word檔案的三種方式

2023-05-04 18:01:15

SpringBoot匯出Word檔案的三種方式

一、匯出方案

.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> &nbsp; &nbsp; &nbsp; 我是資料:{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>&nbsp;</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>&nbsp;</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>&nbsp;</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>&nbsp;</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>&nbsp;</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>&nbsp;</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檔案
  • 文中使用到的檔案:

https://files.cnblogs.com/files/blogs/787464/SpringBoot匯出Word檔案的三種方式-檔案.rar?t=1683184411&download=true