简体   繁体   中英

(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. (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. 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)
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM