【SheetJS】导出excel
背景
在工作中我们需要对后端返回的数据,然后导出excel进行展示。
注意:
SheetJS
只支持普通的导出,如果想要支持丰富的功能(比如:修改导出excel表格的样式或者数据验证等等)就需要使用付费版。excel表格的样式等更高级的功能我们可以使用其他第三方库(exceljs
)实现
步骤
安装依赖
npm i xlsx@0.18.5
基本使用
<template>
<div class="app">
<button @click="exportExcel">点击导出excel</button>
</div>
</template>
<script>
import * as XLSX from "xlsx";
export default {
methods: {
async exportExcel() {
// 文件名称
var filename = "测试1.xlsx";
//数据,一定注意需要时二维数组
var data = [
[1, 2, 3],
[true, false, null, "sheetjs"],
["foo", "bar", new Date("2014-02-19T14:30Z"), "0.3"],
["baz", null, "qux"],
];
//Excel第一个sheet的名称
var ws_name = "sheet(1)";
// 创建sheet
var ws = XLSX.utils.aoa_to_sheet(data);
// 创建wokbook
var wb = XLSX.utils.book_new();
// 将数据添加到工作薄
XLSX.utils.book_append_sheet(wb, ws, ws_name);
// 导出文件
XLSX.writeFile(wb, filename);
},
},
};
</script>
<style scoped></style>
手动拼成二维数组
<template>
<div class="app">
<button @click="exportExcel">点击导出excel</button>
</div>
</template>
<script>
import * as XLSX from "xlsx";
export default {
methods: {
async exportExcel() {
const tableData = [
{ id: 1, name: "张三", age: 18 },
{ id: 2, name: "李四", age: 16 },
{ id: "3", name: "王天霸", age: 20 },
];
// 表头顺序以及表头与字段映射
const excel_map = [
{ label: "ID", prop: "id" },
{ label: "Name", prop: "name" },
{ label: "Age", prop: "age" },
];
let newData = tableData.map((item) => {
let row = [];
for (let o of excel_map) {
row.push(item[o["prop"]]);
}
return row;
});
// 添加表头
const excel_label = excel_map.map((item) => item.label);
newData.unshift(excel_label);
var filename = "测试2.xlsx";
var ws_name = "sheet(2)";
var ws = XLSX.utils.aoa_to_sheet(newData);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, ws_name);
XLSX.writeFile(wb, filename);
},
},
};
</script>
<style scoped></style>
JSON数组
上面需要自己手动去转换,效率低,我们可以使用XLSX.utils.json_to_sheet
的方法
<template>
<div class="app">
<button @click="exportExcel">点击导出excel</button>
</div>
</template>
<script>
import * as XLSX from "xlsx";
export default {
methods: {
async exportExcel() {
let tableData = [
{
id: 1,
name: "张三",
age: 18,
address: "广州市",
hire_date: "2023-06-03",
},
{ id: 2, name: "李四", age: 16 },
{ id: "3", name: "王五", age: 20, from: "广州" },
];
const excel_map = [
{ label: "ID", prop: "id" },
{ label: "Name", prop: "name" },
{ label: "Age", prop: "age" },
{ label: "雇佣日期", prop: "hire_date" },
];
var filename = "测试.xlsx";
var ws_name = "sheet name";
// 默认情况下会在excel加载对象的所有key,我们只需要根据header获取我们需要的数据
const export_data = tableData.map((item) => {
let obj = {};
for (let o of excel_map) {
obj[o.prop] = item[o.prop];
}
return obj;
});
// 自定义表头
const first_row = {};
for (let o of excel_map) {
first_row[o.prop] = o.label;
}
export_data.unshift(first_row);
var ws = XLSX.utils.json_to_sheet(export_data, {
// 默认情况下,插件会帮你设置表头,但是它是用对象的键进行设置,我们表头一般想要单词或者中文的,但是这种作为对象的键就不友好了
skipHeader: true,
});
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, ws_name);
XLSX.writeFileXLSX(wb, filename);
},
},
};
</script>
<style scoped></style>