为 Excel 中的每行数据返回 JSON 对象

我正在为 SheetJS 使用 webpack。我对 webpack 比较陌生,而且对 SheetJS 完全是新手。我不想返回Excel 数据的一个JSON 对象,而是想为Excel 中的每一行数据返回一个 JSON 对象。


输入 Excel 布局示例:


Col1     Col2      Col3

A2       B2        C2

A3       B3        C3

此示例中的理想输出是 2 个 JSON 对象:


JSON 1:


{   

 "A2": [

        {

           "Col1": "A2"

           "Col2": "B2"

           "Col3": "C2"

        }

    ]

}

JSON 2:


 {   

    "A3": [

        {

           "Col1": "A3"

           "Col2": "B3"

           "Col3": "C3"

        }

    ]

 }

尝试的解决方案:


var to_json_linebyline = function to_json_linebyline(wb){

    var sheet = wb.Sheets['Sheet1'];

    var result = {};

    var row, rowNum, colNum;

    var range = XLSX.utils.decode_range(sheet['!ref']);

    for(rowNum = range.s.r; rowNum <= range.e.r-2; rowNum++){

    row = [];

       for(colNum=range.s.c; colNum<=range.e.c; colNum++){

          var nextCell = sheet[

          XLSX.utils.encode_cell({r: rowNum, c: colNum})

       ];

       if( typeof nextCell === 'undefined' ){

          row.push(void 0);

       } else row.push(nextCell.w);

       }

       result[nextCell.v] = row;

    }

    return JSON.stringify(result, 2, 2);

}

当前结果:


{

  "Col3": [

    "Col1",

    "Col2",

    "Col3"

  ],

  "C2": [

    "A2",

    "B2",

    "C2"

  ],

  "C3": [

    "A3",

    "B3",

    "C3"

  ]

}

任何朝着正确方向发展的事情都会很棒。如果它有帮助,这里是github 存储库..谢谢!



子衿沉夜
浏览 107回答 1
1回答

慕慕森

你的意图是正确的,代码是错误的。您正在定义数据并将其推送到数组中,而不是创建 JSON 对象。尝试这个。var to_json_linebyline = function to_json_linebyline(wb){&nbsp; &nbsp; var sheet = wb.Sheets['Sheet1'];&nbsp; &nbsp; var results = [];&nbsp; &nbsp; var range = XLSX.utils.decode_range(sheet['!ref']);&nbsp; &nbsp; for(let rowNum = (range.s.r+1); rowNum <= range.e.r; rowNum++){&nbsp; &nbsp; &nbsp; &nbsp;let thisRow = {},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;thisNode = '';&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;for(let colNum=range.s.c; colNum<=range.e.c; colNum++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var thisHeader = sheet[XLSX.utils.encode_cell({r: 0, c: colNum})].w&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var thisCell = sheet[XLSX.utils.encode_cell({r: rowNum, c: colNum})].w&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(colNum === 0){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; thisNode = thisCell;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; thisRow[thisHeader] = thisCell;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;thisResult = {};&nbsp; &nbsp; &nbsp; &nbsp;thisResult[thisNode] = [thisRow]&nbsp; &nbsp; &nbsp; &nbsp;results.push(thisResult)&nbsp; &nbsp; }&nbsp; &nbsp; return JSON.stringify(results);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript