xlsx.js导出json为execl,以及导入excel解析json
				
									
					
					
						|  | 
							admin 2025年4月13日 15:18
								本文热度 1397 | 
					
				 
				在 JavaScript 中,可以使用 xlsx 库来实现导出 JSON 数据为 Excel 文件以及解析 Excel 文件为 JSON 数据。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(`数据已导出到 ${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 文件时出错:', 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 数据:', parsedJson);}
阅读原文:原文链接
该文章在 2025/4/14 10:24:28 编辑过