[英](Parsing .xlsx -> .json) TypeError: Cannot read properties of undefined (reading 'length')
I'm trying to parse an excel file to create a json output file.我正在尝试解析一个 excel 文件来创建一个 json 输出文件。 (Btw, I'm new to backend development.) This is the error I'm getting:
(顺便说一句,我是后端开发的新手。)这是我得到的错误:
TypeError: Cannot read properties of undefined (reading 'length')
at convertExcelFileToJsonUsingXlsx (/Users/akhilancraja/Development/Dishcovery/SERVER/server/dishcovery-server/src/main.ts:45:38)
at bootstrap (/Users/akhilancraja/Development/Dishcovery/SERVER/server/dishcovery-server/src/main.ts:33:1)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
I've tried providing a fall back in my code, but the .json output file contains an empty array... (literally, the output is "[]") The original .xlsx file has cells that are purposely empty, so I'm not sure if that relates to the issue.我试过在我的代码中提供一个后备,但是 .json 输出文件包含一个空数组......(字面意思是输出是“[]”)原始 .xlsx 文件有故意为空的单元格,所以我'不确定这是否与问题有关。 Here's my code:
这是我的代码:
//07/20/22: Testing
//Bring in installed package as a dependency
const xlsx = require('xlsx');
//Accessing filesystem
var fs = require('fs');
//Function call
convertExcelFileToJsonUsingXlsx();
//This function converts our excel file to json
function convertExcelFileToJsonUsingXlsx(){
//Read the file using the pathname
const file = xlsx.readFile(`/Users/akhilancraja/Development/Dishcovery/SERVER/server/dishcovery-server/src/BusinessInfo.xlsx`);
//Grab sheet info from the file
const sheetNames = file.sheetNames;
//const totalSheets = (sheetNames || []).length; //Providing empty array fallback
const totalSheets = (sheetNames).length;
//Variable to store our data
let parsedData = [];
//Loop through sheets
for(let i = 0; i < totalSheets; i++){
//Convert to json using xlsx
const tempData = xlsx.utils.sheet_to_json(file.Sheets.sheetNames[i]);
//Skip header row which is the column names
tempData.shift();
//Add the sheet's json to our data arrray
parsedData.push(...tempData);
}
//Call a function to save the data in a json file
generateJSONFile(parsedData);
}
//This function stores our excel data in a JSON file on our server
function generateJSONFile(data: any){ //Explicity type-casting data as 'any' to solve implicit type-casting error
try{
fs.writeFileSync('BusinessInfo.json', JSON.stringify(data))
} catch (ERROR) {
console.error(ERROR)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.