<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>从 ZIP 导出大文件 Excel</title> <script src="https://ss.netnr.com/jszip@3.10.1/dist/jszip.min.js"></script> <script src="https://ss.netnr.com/xlsx@0.18.5/dist/xlsx.full.min.js"></script> </head> <body> <p>从 ZIP 导出大文件 Excel</p> <small>示例压缩包约 668KB ,原始文件约 5.6MB,下载解压读取文本再解析为 JSON 数组,再填充 Excel,最后下载 Excel 约 14MB,是压缩的 21倍</small> <input class="nr-ziplink" placeholder="JSON 文件压缩为 ZIP 的下载链接" value="https://ss.netnr.com/tmp/stats-zoning-4.zip" /> <button class="nr-export">导出</button> <small>请打开浏览器控制台看输出</small> </body> </html>
* { color: deeppink; } input { width: 100%; margin: 1em 0; }
var zipLink = document.querySelector('.nr-ziplink'); var exportBtn = document.querySelector('.nr-export'); exportBtn.addEventListener('click', function () { exportExcelFromZip(zipLink.value); }); function exportExcelFromZip(url) { console.debug("下载包...") fetch(url).then(function (response) { return response.arrayBuffer(); }).then(function (buffer) { console.debug("读取包...") var zip = new JSZip(); zip.loadAsync(buffer).then(function (contents) { console.debug("提取文件...") Object.keys(contents.files).forEach(function (filename) { zip.files[filename].async('string').then(function (content) { console.debug("JSON解析...") var json = JSON.parse(content.trim()) console.debug(json) console.debug("转换为 Excel...") filename = filename.split('.')[0]; // 去掉后缀 var header = Object.keys(json[0]); var workbook = XLSX.utils.book_new(); var worksheet = XLSX.utils.json_to_sheet(json, { header: header }); XLSX.utils.book_append_sheet(workbook, worksheet, filename); console.debug("生成 Excel...") XLSX.writeFile(workbook, filename + ".xlsx"); }) }); }); }); }