前端页面导出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>
相关推荐
Mintopia32 分钟前
🌀曲面细分求交:在无限细节中捕捉交点的浪漫
前端·javascript·计算机图形学
Mintopia35 分钟前
🧙‍♂️用 Three.js 判断一个点是否在圆内 —— 一次圆心和点的对话
前端·javascript·three.js
liliangcsdn1 小时前
mac mlx大模型框架的安装和使用
java·前端·人工智能·python·macos
CssHero1 小时前
基于vue3完成领域模型架构建设
前端
PanZonghui1 小时前
用项目说话:我的React博客构建成果与经验复盘
前端·react.js·typescript
言兴1 小时前
教你如何理解useContext加上useReducer
前端·javascript·面试
sunbyte1 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | GoodCheapFast(Good - Cheap - Fast三选二开关)
前端·javascript·css·vue.js·tailwindcss
前端的日常1 小时前
网页视频录制新技巧,代码实现超简单!
前端
前端的日常1 小时前
什么是 TypeScript 中的泛型?请给出一个使用泛型的示例。
前端
今禾1 小时前
一行代码引发的血案:new Array(5) 到底发生了什么?
前端·javascript·算法