vue xlsx 数据导出
1、安装xlsx插件
C/C++ Code复制内容到剪贴板
- npm install xlsx -S
- ## yarn
- yarn add xlsx
2、vue2与vue3的引用方式
值得注意的是再引用xlsx的时候vue3和vue2写法不同
vue2:import XLSX from ‘xlsx’
vue3:import * as XLSX from ‘xlsx’
3、导出
JavaScript Code复制内容到剪贴板
- export default {
- data() {
- return {
- tableData: [
- { name: '张三', age: 18, gender: '男' },
- { name: '李四', age: 20, gender: '女' },
- { name: '王五', age: 22, gender: '男' }
- ]
- }
- },
- methods: {
- exportData() {
- const headers = ['姓名', '年龄', '性别']
- const data = this.tableData.map(item => [item.name, item.age, item.gender])
- const worksheet = XLSX.utils.aoa_to_sheet([headers, ...data])
- const workbook = XLSX.utils.book_new()
- XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
- XLSX.writeFile(workbook, 'data.xlsx')
- }
- }
- }