1、安装插件
npm install file-saver --save
npm install xlsx --save
2、使用(方法二只用安装 xlsx 就可以导出数据)
方法一:
<template>
<div>
<el-button size="mini" class="none-radius" @click="handleExport">导出</el-button>
<el-table id="exportTable" :data="tableData" style=" 100%">
<el-table-column prop="userName" label="姓名" width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="sex" label="性别" width="70" align="center" :show-overflow-tooltip="true">
<template slot-scope="scope">{{scope.row.sex | sexList}}</template>
</el-table-column>
...
</el-table>
</div>
</template>
<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
methods() {
handleExport() {
this.$confirm('该操作将导出所有列表数据,是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
let exportTable = XLSX.utils.table_to_book(document.querySelector('#exportTable'))
let exportTableOut = XLSX.write(exportTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([exportTableOut], { type: 'application/octet-stream' }), '表格名称.xlsx')
} catch (e) { if (typeof console !== 'undefined') console.log(e, exportTableOut) }
return exportTableOut;
}).catch(() => { });
},
}
}
方法二:
<template>
<div>
<el-button size="mini" class="none-radius" @click="handleExport">导出</el-button>
<el-table id="exportTable" :data="tableData" style=" 100%">
<el-table-column prop="userName" label="姓名" width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="sex" label="性别" width="70" align="center" :show-overflow-tooltip="true">
<template slot-scope="scope">{{scope.row.sex | sexList}}</template>
</el-table-column>
...
</el-table>
</div>
</template>
<script>
import XLSX from 'xlsx'
export default {
methods: {
handleExport() {
this.$confirm('该操作将导出选中的列表数据,是否继续', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//导出
let table = document.getElementById('exportTable');
let worksheet = XLSX.utils.table_to_sheet(table);
let workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet');
try {
XLSX.writeFile(workbook, '文档ll.xlsx');
} catch (e) {
console.log(e, workbook);
}
}).catch(() => { });
},
}
}