前端页面导出word

html-docx-js bug:

vite使用html-docx.js会报错,点击下载上方文件替换即可

正文

bash 复制代码
npm install html-docx-js -S
npm install file-saver -S
javascript 复制代码
<template>
 <div id="managerReport">
	 word内容......
 </div>
</template>

<script>
 <a-button type="primary" @click="wordDownload"> 导出 </a-button>
  function wordDownload() {
    const htmlContent = document.getElementById('managerReport');

    // 查找并修改表格的样式
    const tables = htmlContent.querySelectorAll('table');
    tables.forEach((table) => {
      table.style.borderCollapse = 'collapse';
      table.style.width = '100%';

      table.querySelectorAll('td, th').forEach((cell, index) => {
        if (cell) {
          cell.style.border = '1px solid black';
          cell.style.padding = '8px';
        }
      });
    });

    //去除<br>标签,内容加到<div>标签内
    const brs = htmlContent.querySelectorAll('br');
    brs.forEach((br) => {
      const parent = br.parentNode; //获取父节点
      let textNode = br.previousSibling; //前一个兄弟节点
      // while (textNode && textNode.nodeType !== Node.TEXT_NODE) {
      //   textNode = textNode.previousSibling;        //循环查找,直到找到一个文本节点或没有更多的兄弟节点
      // }
      if (textNode && textNode.nodeType === Node.TEXT_NODE && textNode.textContent.trim()) {
        //找到文本节点,并且内容不为空
        const div = document.createElement('div');
        div.textContent = textNode.textContent;
        parent.insertBefore(div, br);

        parent.removeChild(textNode); //移除原有的文本节点,避免内容重复
      } else {
        const div = document.createElement('div');
        div.innerHTML = '&nbsp;';
        parent.insertBefore(div, br);
      }
      parent.removeChild(br);
    });

    const htmlContentCopy = htmlContent.cloneNode(true);

    const imgs = htmlContentCopy.querySelectorAll('img');
    imgs.forEach((img) => {
      let docxWidth = 620;
      if (img.width > docxWidth) {
        img.height = (img.height * docxWidth) / img.width;
        img.width = docxWidth;
      }
    });

    // 将HTML转换为Blob对象
    const blob = asBlob(htmlContentCopy.innerHTML);
    saveAs(blob, `aaaaa.docx`);
  }
  </script>
相关推荐
apcipot_rain21 分钟前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
ShallowLin26 分钟前
vue3学习——组合式 API:生命周期钩子
前端·javascript·vue.js
Nejosi_念旧1 小时前
Vue API 、element-plus自动导入插件
前端·javascript·vue.js
互联网搬砖老肖1 小时前
Web 架构之攻击应急方案
前端·架构
pixle01 小时前
Vue3 Echarts 3D饼图(3D环形图)实现讲解附带源码
前端·3d·echarts
诸葛大钢铁2 小时前
WORD压缩两个免费方法
word
KingCruel2 小时前
NPOI 操作 Word 文档
word
麻芝汤圆2 小时前
MapReduce 入门实战:WordCount 程序
大数据·前端·javascript·ajax·spark·mapreduce
juruiyuan1114 小时前
FFmpeg3.4 libavcodec协议框架增加新的decode协议
前端
Peter 谭4 小时前
React Hooks 实现原理深度解析:从基础到源码级理解
前端·javascript·react.js·前端框架·ecmascript