浏览器把JSON导出转为excel下载到本地
Author:[email protected] Date:
JSON to excel文件下载,npm包搜了一下https://www.npmjs.com/search?q=json%20to%20excel
最近选择xlxs库,看官方代码:https://docs.sheetjs.com/docs/getting-started/example/
<body> <script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script> <script> (async() => { /* fetch JSON data and parse */ /* flatten objects */ const rows = [ { "COUNT(create_by)": 41, "COUNT(DISTINCT biz_id)": 1, "biz_id": "-1", "_unique_metric_": "-1" }, { "COUNT(create_by)": 1564, "COUNT(DISTINCT biz_id)": 1, "biz_id": "100140", "_unique_metric_": "100140" }, ]; /* generate worksheet and workbook */ const worksheet = XLSX.utils.json_to_sheet(rows); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "Dates"); /* create an XLSX file and try to save to Presidents.xlsx */ XLSX.writeFile(workbook, "Presidents.xlsx", { compression: true }); })(); </script> <body>
是可以的,但是本地无法加载,发现报:typescript referenceError: require is not defined
他们的,发现npm i 直接安装不行,
只有这样才可以:
npm i --save https://cdn.sheetjs.com/xlsx-0.19.3/xlsx-0.19.3.tgz
详情见官方文档:https://docs.sheetjs.com/docs/getting-started/installation/frameworks
xlxs库发现按需加载不行:
import { writeFile, utils } from 'xlsx';
不知道如何处理。
详情代码如下
下载文件代码:
// import { writeFile, utils } from 'xlsx'; import XLSX from 'xlsx'; export default function ( rows: Record<string, string>[], title = `${new Date().getTime()}`, ) { if (!rows.length) { return; } /* generate worksheet and workbook */ const worksheet = XLSX.utils.json_to_sheet(rows); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Dates'); /* create an XLSX file and try to save to Presidents.xlsx */ XLSX.writeFile(workbook, `${title}.xlsx`, { compression: true }); }
转载本站文章《浏览器把JSON导出转为excel下载到本地》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/js/2015_0924_298.html