安装
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
Vue.prototype.$FileSaver = FileSaver
Vue.prototype.$XLSX = XLSX
<template>
<!-- 下载为EXCEL -->
<span>
<el-button type="primary" @click="toExcell(data)">下载</el-button>
</span>
</template>
<script>
export default {
props: ['data'],
computed: {
iframeData () {
return this.$store.getters.getData
}
},
methods: {
downloadExl (data) {
var keys = Object.keys(data[0])
var firstRow = {}
keys.forEach(function (item) {
firstRow[item] = item
})
data.unshift(firstRow)
var content = {}
// 把json格式的数据转为excel的行列形式
var sheetsData = data.map(function (item, rowIndex) {
return keys.map(function (key, columnIndex) {
return Object.assign({}, {
value: item[key],
position: (columnIndex > 25 ? this.getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1)
})
})
}).reduce(function (prev, next) {
return prev.concat(next)
})
sheetsData.forEach(function (item, index) {
content[item.position] = {
v: item.value
}
})
// 设置区域,比如表格从A1到D10,SheetNames:标题,
var coordinate = Object.keys(content)
var workBook = {
SheetNames: ['helloSheet'],
Sheets: {
'helloSheet': Object.assign({}, content, {
'!ref': coordinate[0] + ':' + coordinate[coordinate.length - 1]
})
}
}
// 这里的数据是用来定义导出的格式类型
var excelData = this.$XLSX.write(workBook, {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
})
var blob = new Blob([this.string2ArrayBuffer(excelData)], {
type: ''
})
this.$FileSaver.saveAs(blob, 'hello.xlsx')
},
// 字符串转字符流
string2ArrayBuffer (s) {
var buf = new ArrayBuffer(s.length)
var view = new Uint8Array(buf)
for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
return buf
},
// 将指定的自然数转换为26进制表示。映射关系:[0-25] -> [A-Z]。
getCharCol (n) {
let s = ''
let m = 0
while (n > 0) {
m = n % 26 + 1
s = String.fromCharCode(m + 64) + s
n = (n - m) / 26
}
return s
},
exportExcel (id) {
/* generate workbook object from table */
var wb = this.$XLSX.utils.table_to_book(
document.querySelector(id)
)
/* get binary string as output */
var wbout = this.$XLSX.write(wb, {
bookType: 'xlsx',
bookSST: true,
type: 'array'
})
try {
this.$FileSaver.saveAs(
new Blob([wbout], {
type: 'application/octet-stream'
}),
'sheetjs.xlsx'
)
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout)
}
return wbout
},
toExcell (data) {
if (typeof data === 'object') {
this.downloadExl(data)
} else {
this.exportExcel(data)
}
}
}
}
</script>
<style scoped>
</style>
<ToExcel data="#out-table" />//id
或者
<ToExcel :data="tableData" />//数据