1.安装并引用excle库
npm install -S file-saver xlsx
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
2.利用表格dom导出
exportTableDom2Excel(dom, title = '导出表格') {
if (!this.$refs[dom]) {
console.log('dom未加载')
return
}
let xlsxParam = { raw: true }
let wb = XLSX.utils.table_to_book(this.$refs[dom].$el, xlsxParam)
let wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${title}.xlsx`)
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout)
}
return wbout
}
3.利用表格数据导出
exportTableJson2Excel(data, header, title = '导出表格') {
const ws = XLSX.utils.json_to_sheet(data, { header })
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, 'sheet1')
XLSX.writeFile(wb, `${title}.xlsx`)
}
4.图片导出
npm install -S html2canvas xlsx
import html2canvas from 'html2canvas'
exportImg(chartdom, title = '导出图片') {
if (!this.$refs[chartdom]) {
console.log('dom未加载')
return
}
window.pageYoffset = 0
document.documentElement.scrollTop = 0
document.body.scrollTop = 0
const dom = this.$refs[chartdom].$el
const width = dom.offsetWidth
const height = dom.offsetHeight
const scale = 2
html2canvas(dom, {
width: width,
heigth: height,
backgroundColor: '#ffffff',
dpi: window.devicePixelRatio * 2,
scale: scale,
X: 0,
Y: 0,
scrollX: -3,
scrollY: 0,
useCORS: true,
allowTaint: true
}).then(canvas => {
const url = canvas.toDataURL()
const a = document.createElement('a')
a.download = `${title}.png`
const event = new MouseEvent('click')
a.href = url
a.dispatchEvent(event)
})
}