前端页面导出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>
相关推荐
IT_陈寒1 分钟前
Vite5.0性能翻倍秘籍:7个极致优化技巧让你的开发体验飞起来!
前端·人工智能·后端
xw513 分钟前
uni-app项目Tabbar实现切换icon动效
前端·uni-app
凉、介21 分钟前
U-Boot 多 CPU 执行状态引导
java·服务器·前端
时光少年29 分钟前
Android 喷雾效果实现
android·前端
南囝coding37 分钟前
Claude 封禁中国?为啥我觉得是个好消息
前端·后端
wordbaby1 小时前
备忘录模式(Memento Pattern)详解
前端
小鱼儿亮亮1 小时前
二、React基础精讲:编写TodoList、事件绑定、JSX语法、组件之间传值
前端·react.js
Mintopia1 小时前
实时 AIGC:Web 端低延迟生成的技术难点与突破
前端·javascript·aigc
小鱼儿亮亮1 小时前
五、Redux进阶:UI组件、容器组件、无状态组件、异步请求、Redux中间件:Redux-thunk、redux-saga,React-redux
前端·react.js
Mintopia1 小时前
Next.js 性能优化双绝:Image 与 next/font 的底层修炼手册
前端·javascript·next.js