html导出docx文件
方法一、技术实现:fileSaver.js+html-docx-js
html-docx.js,这个比较是16年的插件,不适合现在的,主要就是with(obj){}这个已经不符合规范,有的框架不适用
1.npm安装
$ npm install --save html-docx-js
$ npm install --save file-saver
2.引入
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
3.导出word
<template>
<div class="about">
<button @click="this.exportClick">an</button>
</div>
</template>
<script>
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
export default {
methods: {
exportClick() {
var content = ` <h1>This is an about page</h1>
<h2>This is an about page</h2>`
var page = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' + content + '</body></html>'
var converted = htmlDocx.asBlob(page);
// 用 FielSaver.js里的保存方法 进行输出
saveAs(converted, 'test.docx');
}
}
}
</script>
方法二:jQuery中的插件jquery.wordexport.js+fileSaver.js
说明:在Vue中使用
1.在index.html全局引入jQuery
2.cmd安装FileSaver.js , 在需要的组件中引入file-saver
npm install file-saver --save
3.在需要的组件中引入
4.使用
<div class="word">
<h1>我们的梦想来自内心深处的孤独</h1>>
<p align="center" style="font-size:20pt;font-weight:bold;">JS导出Word文档</p>
<div>我们来自同一个世界</div>
</div>
<input type="button" value="导出word">
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
<script type="text/javascript" src="FileSaver.js"></script>
<script type="text/javascript" src="jquery.wordexport.js"></script>
<script>
$(function () {
$("input[type='button']").click(function (event) {
$(".word").wordExport('word文档');
});
})
</script>
可以使用xdoc http://www.xdocin.com/web.html
table导出excel
1. 安装依赖
npm install --save xlsx
npm install --save file-saver
2. 表格添加属性
标签添加ref属性,用于获取该元素el;也可添加id属性获取
<table ref="exportTableRef"> ... </table>
或
<table id="table" > ... </table>
3. js代码
// 导入依赖
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
// 导出方法
exportBtn() {
// 获取表格元素
const el = this.$refs.exportTableRef1.$el
// 文件名
const filename = '导出.xlsx'
/* generate workbook object from table */
const wb = XLSX.utils.table_to_book(el)
/* 或者用id */
// const wb = XLSX.utils.table_to_book(document.getElementById("id"))
/* get binary string as output */
const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
} catch (e) {
console.log(e)
}
return wbout
}