vue项目里使用纯js实现将页面导出为word

博客主要围绕DOM部分展开,提到样式可通过字符串拼接方式处理,还展示了页面效果以及导出的Word效果,涉及JavaScript和Vue.js相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dom部分

<template>
  <div>
    <button @click="wordExport">点击导出为word</button>
    <div id="wordTest">
      <p>这是一个word</p>
      <table style="border:1px solid">
        <thead>
          <th>文本1</th>
          <th>文本2</th>
          <th>文本3</th>
          <th>文本4</th>
        </thead>
        <tbody>
          <tr>
            <td>NO.1</td>
            <td>NO.2</td>
            <td>NO.3</td>
            <td>NO.4</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

样式可以通过字符串拼接的方式将

wordExport() {
      let header =
        "<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
        "xmlns:w='urn:schemas-microsoft-com:office:word' " +
        "xmlns='http://www.w3.org/TR/REC-html40'>" +
        "<head><meta charset='utf-8'><title>Export HTML to Word Document with JavaScript</title></head><body>" +
        "<style type='text/css'>p{text-align: center;};table{width:100%};th {background: red;color: blue;} th,tr,td{border:1px solid;text-align: center;};</style>";
      let footer = "</body></html>";
      let sourceHTML =
        header + document.getElementById("wordTest").innerHTML + footer;
      let source =
        "data:application/vnd.ms-word;charset=utf-8," +
        encodeURIComponent(sourceHTML);
      let fileDownload = document.createElement("a");
      document.body.appendChild(fileDownload);
      fileDownload.href = source;
      fileDownload.download = "document.doc";
      fileDownload.click();
      document.body.removeChild(fileDownload);
    }
  }

最后效果图显示:
页面中的效果:
在这里插入图片描述
导出的word效果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值