前端页面导出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>
相关推荐
zwjapple3 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
像风一样自由20205 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
zzc9215 小时前
Adobe Illustrator设置的颜色和显示的颜色不对应问题
adobe·bug·illustrator·错误·配色·透明度·底色
aiprtem5 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊6 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术6 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing6 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止6 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall6 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴6 小时前
简单入门Python装饰器
前端·python