前端页面导出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>
相关推荐
Hyyy6 小时前
普通前端续命周报——第1周
前端·javascript
KaMeidebaby6 小时前
卡梅德生物技术快报|抗独特型抗体开发:半抗原检测技术瓶颈拆解,抗独特型抗体开发工程化实践
前端·数据库·人工智能·其他·百度·新浪微博
2501_940041746 小时前
纯前端创意交互:五款全新实用工具与视觉应用生成指南
前端·交互
刀法如飞6 小时前
《道德经》简单解说版-第 2 章:天下皆知美之为美
前端·后端·面试
发现一只大呆瓜8 小时前
超全 Vite 性能优化指南:网络、资源、预渲染三维落地方案
前端·面试·vite
IT_陈寒9 小时前
Vue的computed属性怎么突然不更新了?
前端·人工智能·后端
智商不够_熬夜来凑9 小时前
【Picker】单选多选
前端·javascript·vue.js
米饭不加菜9 小时前
Typora 原生流程图语法完全指南(Flowchart.js)
前端·javascript·流程图
scan72410 小时前
langgraphy条件边
前端·javascript·html
冰小忆10 小时前
类变量在继承场景下的初始化规则是怎样的?
java·前端·数据库