Use XLSX.utils.sheet_to_json () parses excel, assigned to the empty cell empty string

Foreword

Today XLSX used to parse the excel file, call XLSX.utils.sheet_to_json (worksheet), found that if the cell is empty, then parse out the results, it will lack the appropriate key (as shown). But I want the cell is empty, then the value will default to an empty string, how to do it? Only to see the source code to see if there is no way to default values.
Here Insert Picture DescriptionHere Insert Picture Description

Source Exploration

Where to find the source of sheet_to_json () method, the method found three of the same name, there are two arguments, the first worksheet is a Workbook object to parse excel file, the second parameter ?: Sheet2JSONOpts the opts,
? Indicate that this parameter is optional, you do not pass will not, Sheet2JSONOpts what this is? I do not know, can only be read on the source has not defined this thing. (Usually there)
Here Insert Picture Description
Sure enough, as I expected, finally found Sheet2JSONOpts defined in the source code and found that five variables, these five variables have brought? To prove that the five variables are optional. Then I saw the red line portion in the figure, found that the written comments Default value for null / undefined values, meaning that the default value is null or undefined value of the variable. It is not that the solution I'm looking for yet? Happy rush to implement it.
Here Insert Picture Description

solve

The second source is defined in accordance with parameters assigned to defval empty string, as shown in the code

const sheet2JSONOpts = {
        /** Default value for null/undefined values */
        defval: ''//给defval赋值为空的字符串
}
//调用方法
const results = XLSX.utils.sheet_to_json(worksheet, sheet2JSONOpts)
console.log(results)

Finally, the results of a successful solution to my problem, as shown below
Here Insert Picture Description

to sum up

With some plug-ins, when some of the problems, in fact, can find a good solution by looking at the source code, a good plug-in package some way, to give us a call.

Published 14 original articles · won praise 6 · views 6324

Guess you like

Origin blog.csdn.net/weixin_43817709/article/details/103754546