在 JavaScript 中,可以使用 xlsx 庫(kù)來實(shí)現(xiàn)導(dǎo)出 JSON 數(shù)據(jù)為 Excel 文件以及解析 Excel 文件為 JSON 數(shù)據(jù)。const XLSX = require('xlsx');const fs = require('fs');const path = require('path');
function exportJsonToExcel(jsonData, filePath) { const worksheet = XLSX.utils.json_to_sheet(jsonData); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); XLSX.writeFile(workbook, filePath); console.log(`數(shù)據(jù)已導(dǎo)出到 ${filePath}`);}
function parseExcelToJson(filePath) { try { const workbook = XLSX.readFile(filePath); const firstSheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[firstSheetName]; const jsonData = XLSX.utils.sheet_to_json(worksheet); return jsonData; } catch (error) { console.error('解析 Excel 文件時(shí)出錯(cuò):', error); return null; }}
const sampleJson = [ { name: 'John', age: 30, city: 'New York' }, { name: 'Jane', age: 25, city: 'Los Angeles' }, { name: 'Bob', age: 35, city: 'Chicago' }];
const exportFilePath = path.join(__dirname, 'output.xlsx');exportJsonToExcel(sampleJson, exportFilePath);
const parsedJson = parseExcelToJson(exportFilePath);if (parsedJson) { console.log('解析后的 JSON 數(shù)據(jù):', parsedJson);}
還有更復(fù)雜的用法可以去參考xlsx的官方文檔
閱讀原文:原文鏈接
該文章在 2025/4/14 10:24:28 編輯過