1.安装依赖
npm install html-docx-js -S
npm install file-saver -S
file-saver是用来保存文件的,也是必须安装的。
2.表格或其他html标签(也可用ref属性)
<table id="id"> ... </table>
3.js代码
// 导入依赖
import FileSaver from 'file-saver'
import htmlDocx from "html-docx-js/dist/html-docx"
//模板word导出
exportWordTpl() {
let contentHtml = document.getElementById("id").innerHTML
let cssHTML = `
table {
width: 100%;
table-layout: fixed;
margin-top:10px;
border: 1px solid #ddd;
border-collapse: collapse;
}
.export-tb .thead td {
font-weight: bold;
}
td {
border: 1px solid #ddd;
color: #333;
text-align: left;
padding: 6px 10px;
}`
let content = `
<!DOCTYPE html><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
${cssHTML}
</style>
</head>
<body>
<table>
${contentHtml}
</table>
</body>
</html>`;
let converted = htmlDocx.asBlob(content);
FileSaver.saveAs(converted, '文件名.docx');
}