JSON 导出为 Excel
基本结构
页面内容也非常简单,具体如下:
<template> <div id="container"> <h1>JSON 数据:</h1> <h2> <code> {{ jsonData }} </code> </h2> <button @click="exportExcel">导出 Excel</button> </div> </template> 复制代码
导出功能
导出其实也很简单,首先创建 src/utils/json2Excel.ts
文件里面就是具体导出的实现,具体内容如下:
// src/utils/json2Excel.ts import * as XLSX from "xlsx"; export default ( data: any[], sheetName: string = "sheet1", fileName: string = "json2Excel.xlsx" ) => { const jsonWorkSheet = XLSX.utils.json_to_sheet(data); const workBook = { SheetNames: [sheetName], // 指定有序 sheet 的 name Sheets: { [sheetName]: jsonWorkSheet, // 表格数据内容 }, }; return XLSX.writeFile(workBook, fileName); // 向文件系统写出文件 }; 复制代码
然后在 App.vue
中使用,具体如下:
// src/App.vue <script setup lang="ts"> import json2Excel from "./utils/json2Excel"; // 测试的 JSON 数据 const jsonData = [ { name: "张三1", age: 18, skill: "干饭1", telephone: 20200825, address: "宇宙尽头1", }, { name: "张三2", age: 19, skill: "干饭2", telephone: 20200826, address: "宇宙尽头2", }, { name: "张三3", age: 20, skill: "干饭3", telephone: 20200827, address: "宇宙尽头3", }, { name: "张三4", age: 21, skill: "干饭4", telephone: 20200828, address: "宇宙尽头4", }, { name: "张三5", age: 22, skill: "干饭5", telephone: 20200829, address: "宇宙尽头5", }, { name: "张三6", age: 23, skill: "干饭6", telephone: 20200830, address: "宇宙尽头6", }, { name: "张三7", age: 24, skill: "干饭7", telephone: 20200831, address: "宇宙尽头7", }, { name: "张三8", age: 25, skill: "干饭8", telephone: 20200832, address: "宇宙尽头8", }, { name: "张三9", age: 26, skill: "干饭9", telephone: 20200833, address: "宇宙尽头9", }, { name: "张三10", age: 27, skill: "干饭10", telephone: 20200834, address: "宇宙尽头10", }, ]; // key -> name 的映射 const excelKeyToName = { name: "姓名", age: "年龄", skill: "特长", telephone: "电话", address: "地址", }; // 导出 Excel 文件 const exportExcel = () => { // 格式化参数 const data = jsonData.map((item) => { const newItem: any = {}; Object.keys(item).forEach(key => { newItem[excelKeyToName[key]] = item[key]; }); return newItem; }); // 导出 Excel json2Excel(data); }; </script> 复制代码
效果演示
最后
以上只是实现了简单的单个导入、导出功能,可以将其完善为 批量操作,但是要注意批量操作带来的耗时性,将对应的耗时部分通过 webworker
等方式处理,这样页面就不需要一直等待当前的操作完成。
另外,如果有要求在导出 Excel
时有表格样式(如:行列宽高设置等)可以通过 xlsx-populate
来实现。
以上就是本文的全部内容,希望上述内容可以给大家带来一些思路,可以在评论区贡献更优质的方案。