vue+echarts纯前端导出word
图表:echarts
UI:element
安装
npm install docxtemplater pizzip --save
npm install jszip-utils --save
npm install jszip --save
npm install file-saver --save
npm install --save docxtemplater-image-module-free
npm install pizzip --save
引入
import JSZipUtils from 'jszip-utils'
import docxtemplater from 'docxtemplater'
import { saveAs } from 'file-saver'
import PizZip from 'pizzip'
HTML
<el-button @click="exportWord" type="primary">导出word</el-button>
JS
导出图片的设置
getBaseImage(index, chart) {
let img = new Image()
img.src = chart.getDataURL({
pixelRatio: 2, //分辨率
backgroundColor: '#fff', //背景色
})
// 向父组件传图片base64格式
this.setImageBase(index, img.src)
},
导出图base64存入本地
setImageBase(index, url) {
this.imageListBase[index].url = url
},
导出图的格式通过插件渲染
base64DataURLToArrayBuffer(dataURL) {
const base64Regex = /^data:image/(png|jpg|svg|svg+xml);base64,/
if (!base64Regex.test(dataURL)) {
return false
}
const stringBase64 = dataURL.replace(base64Regex, '')
let binaryString
if (typeof window !== 'undefined') {
binaryString = window.atob(stringBase64)
} else {
binaryString = new Buffer(stringBase64, 'base64').toString('binary')
}
const len = binaryString.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i++) {
const ascii = binaryString.charCodeAt(i)
bytes[i] = ascii
}
return bytes.buffer
},
点击导出word
exportWord() {
let ImageModule = require('docxtemplater-image-module-free')
let _this = this
// 读取并获得模板文件的二进制内容
// 模板文件在public文件夹下
JSZipUtils.getBinaryContent('word.docx', function (error, content) {
if (error) {
throw error
}
let opts = {}
opts.centered = true
opts.fileType = 'docx'
opts.getImage = function (chartId) {
return _this.base64DataURLToArrayBuffer(chartId)
}
opts.getSize = function () {
return [800, 450]
}
let imageModule = new ImageModule(opts)
let zip = new PizZip(content)
let doc = new docxtemplater()
doc.attachModule(imageModule)
doc.loadZip(zip)
doc.setData({
//导出的数据
..._this.form,
table: _this.tableData,
table1: _this.tableData1,
imagelist: _this.imageListBase,
})
try {
doc.render()
} catch (error) {
let e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties,
}
throw error
}
let out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
})
saveAs(out, 'echartsWord.docx')
})
},
data数据
form: {
name: '***',
name1: '***',
},
tableData: [],
tableData1: [],
imageListBase: [{ title: '***' }, { title: '***' }, { title: '***' }],
word模板
模板存放于public文件目录下