user12214130
user12214130

Reputation: 158

An error occurs if the number field is empty

I get an error when the field with the number is an empty value.

Value sent to Number function of cells ["F3"] was not a number, it has type of object and value of null

Can this be fixed somehow?

An example of how I fill a table with numerical values:

var styleNumber = wb.createStyle({
    font: {
        color: '#000000',
        size: 14,
        name: 'Times New Roman',
    },
    alignment: {
        horizontal: 'center',
        vertical: 'top'
    }
});

reports.forEach((report, index) => ws.cell(index + 3, 6).number(report._previousDataValues.code).style(styleNumber));

Upvotes: 0

Views: 744

Answers (2)

LeMark
LeMark

Reputation: 21

I've got the same message once. You're probably using some module like excel4node or exceljs, right? The problem rests on the .number(report._previousDataValues.code). Here you´re considering the variable report._previousDataValues.code always as a number. One way to prevent this kind of problem is by testing this variable and write it in the workbook in different formats. Something like this:

reports.forEach((report, index) => { 
if (typeof report._previousDataValues.code === 'number'){
    ws.cell(index + 3, 6).number(report._previousDataValues.code).style(styleNumber)
}else{
    ws.cell(index + 3, 6).string(report._previousDataValues.code).style(styleNumber)
}});

Upvotes: 0

Joost K
Joost K

Reputation: 1116

javascript has a neat trick with the || operator you can use

what it does is return the first value if its a truthy value and the second if it isn't

this would result in

reports.forEach((report, index) => ws.cell(index + 3, 6).number(report._previousDataValues.code || 0).style(styleNumber));

Just to write out what happens with this code:

previousDataValues.code = 1234
(_previousDataValues.code || 0) //returns 1234
previousDataValues.code = null
(_previousDataValues.code || 0) //returns 0
previousDataValues.code = 0
(_previousDataValues.code || 0) //returns 0
previousDataValues.code = -1234
(_previousDataValues.code || 0) //returns -1234

See this answer: https://stackoverflow.com/a/476445/8796313

Upvotes: 0

Related Questions