欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 前端页面导出word

前端页面导出word

2025/2/24 1:01:03 来源:https://blog.csdn.net/weixin_44208050/article/details/144452498  浏览:    关键词:前端页面导出word

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

正文

npm install html-docx-js -S
npm install file-saver -S
<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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词