安装依赖
npm install file-saver --save
npm install xlsx@0.17.0 --save
html
<template>
<div id="app">
<el-button type="primary" @click="exportExcel('表格下载','table')">下载</el-button>
<el-table :data="tableData" stripe style="width: 100%" id="table">
<el-table-column prop="date" label="日期" width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="address" label="地址">
</el-table-column>
</el-table>
</div>
</template>
js
<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import {Message} from 'element-ui'
export default {
name: 'app',
data() {
return {
msg: 'hello word',
tableData: [{
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}]
}
},
methods: {
exportExcel(name, id) {
var wb = XLSX.utils.table_to_book(document.querySelector('#' + id))
var wbout = XLSX.write(wb, {
bookType: 'xlsx',
bookSST: true,
type: 'array'
})
try {
FileSaver.saveAs(new Blob([wbout], {
type: 'application/octet-stream'
}), name + '.xlsx')
Message.success('导出成功!')
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout)
Message.warning("导出失败!")
}
return wbout
}
},
}
</script>
完整代码
<template>
<div id="app">
<el-button type="primary" @click="exportExcel('表格下载','table')">下载</el-button>
<el-table :data="tableData" stripe style="width: 100%" id="table">
<el-table-column prop="date" label="日期" width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="address" label="地址">
</el-table-column>
</el-table>
</div>
</template>
<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import {Message} from 'element-ui'
export default {
name: 'app',
data() {
return {
msg: 'hello word',
tableData: [{
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}]
}
},
methods: {
exportExcel(name, id) {
var wb = XLSX.utils.table_to_book(document.querySelector('#' + id))
var wbout = XLSX.write(wb, {
bookType: 'xlsx',
bookSST: true,
type: 'array'
})
try {
FileSaver.saveAs(new Blob([wbout], {
type: 'application/octet-stream'
}), name + '.xlsx')
Message.success('导出成功!')
} catch (e) {
if (typeof console !== 'undefined') console.log(e, wbout)
Message.warning("导出失败!")
}
return wbout
}
},
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
/* text-align: center; */
color: #2c3e50;
margin-top: 60px;
}
</style>