Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xlsx to json with empty cells

I'm converting a file from xlsx format to json, I can do it correctly, but I could not get it to show the cells that are empty, just ignore them. I am using the XLSX library. This is the code with which I do the parsing.

const workbook = XLSX.readFile(filename);
        const sheet_name_list = workbook.SheetNames;
        let jsonPagesArray = [];
        sheet_name_list.forEach(function(sheet) {
                const jsonPage = {
                    name: sheet,
                    content: XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
                };
                jsonPagesArray.push(jsonPage);
            });
        res.json(
            {
                data:jsonPagesArray
            }
        );
        });

actually if a give this:

xxx1 | xxx2 | xxx3
------------------
yyyy | yyyy | 
zzzz | zzzz | zzzz

it return me:

    [
        {
            xxx1:yyyy,
            xxx2:yyyy
        }
    ],
    [
        {
            xxx1:zzzz,
            xxx2:zzzz,
            xxx3:zzzz
        }
    ]

i want it return me something like this:

    [
        {
            xxx1:yyyy,
            xxx2:yyyy,
            xxx3:""
        }
    ],
    [
        {
            xxx1:zzzz,
            xxx2:zzzz,
            xxx3:zzzz
        }
    ]
like image 634
kmilo93sd Avatar asked Feb 24 '19 13:02

kmilo93sd


3 Answers

can you replace content: XLSX.utils.sheet_to_json(workbook.Sheets[sheet]) with content: XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {defval:""}) in your code and try again?

like image 188
kanhai shah Avatar answered Nov 10 '22 11:11

kanhai shah


This should work. Working example

let XLSX = require('xlsx');
const workbook = XLSX.readFile(filename);
const sheet_name_list = workbook.SheetNames;
let jsonPagesArray = [];
sheet_name_list.forEach(function(sheet) {
        const jsonPage = {
            name: sheet,
            content: JSON.parse(JSON.stringify(XLSX.utils.sheet_to_json(workbook.Sheets[sheet],{defval:""})))
        };
        jsonPagesArray.push(jsonPage);
    });

console.log(jsonPagesArray[0].content);
like image 3
Nafis Islam Avatar answered Nov 10 '22 12:11

Nafis Islam


You can use

XLSX.utils.sheet_to_json(worksheet , {defval:""})
like image 2
Chandra Sagar Avatar answered Nov 10 '22 10:11

Chandra Sagar