js 生成docx文档

420 阅读1分钟

前言

需要实现一个点击下载,把裁剪后的图片和表格数据生成一个docx格式的文件。 废话不多说......

一、安装

    "file-saver": "^2.0.5",
    "html-docx-js": "^0.3.1",

二、引入

   import { saveAs } from "file-saver";
   import htmlToDocx from "html-docx-js/dist/html-docx";

三、在代码中使用

      let t = "";
      let s = "";
      //遍历加载图片
      this.screenshotData.forEach((el, index) => {
        //console.log(el.path);
        let temp = ``;
        if (el.path == "") {
          temp = ``;
        } else {
          temp = `<img width="600" height="300" src="${el.path}" alt="" key="${index}" />`;
        }
        t += `
          <div>
            <div>${el.state}:</div> 
            ${temp}
          </div>
        `;
      });
      
      //遍历生成表格
      this.ProgramSuppliesData.forEach((el) => {
        s += `<tr>
              <th>${el.name}</th>
              <th>${el.value}</th>
            </tr>`;
      });
      
      //模板
      const tableContent = `<!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
        
          <title>多行表格示例</title>
          <style>
            table {
               border-collapse: collapse; /* 使边框收缩 */
               width: 100%; /* 表格宽度 */
            }
            th, td {
               border: 1px solid black; /* 边框颜色为黑色 */
               padding: 8px; /* 单元格内边距 */
               text-align: left; /* 文本对齐方式 */
            }
            .title{
              text-align: center;
              font-size:30px;
              font-weight: bold;
              margin-bottom:20px;
            }
            .image{
              width:600px;
              height:300px;
            }
            .ypsl{
              margin-top:20px;
            }
          </style>
        </head>
        <body>
          <div class="title">北京新国展会议中心布置方案</div>
          <div>
            ${t}
          </div>
          <div class="ypsl">用品数量:</div>
          <table>
            <tr>
              <th>方案用品</th>
              <th>数量</th>
            </tr>
            ${s}
            <!-- 你可以继续添加更多行 -->
          </table>
        </body>
      </html>`;
      // 将表格包裹在段落和文档标签中
      const docContent = `
       <p>Your table list:</p>
        ${tableContent}
      `;

      // 将HTML转换为Docx格式
      const docx = htmlToDocx.asBlob(docContent);

      // 创建Blob对象并导出
      const blob = new Blob([docx], {
        type:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      saveAs(blob, "test.docx");

四、效果展示

微信图片_20241209182437.png

微信图片_20241209182622.png

五、注意事项

1、引入图片时,需要转换成base64;
2、blob格式地址不支持;
3、引入图片img css不支持,需要通过它的属性来设置图片的大小width="" height="";

结语

希望对大家有用。