Angular 2 - парсинг листа Excel в Json - PullRequest
0 голосов
/ 02 июля 2018

У меня есть файл Excel со следующим содержимым: enter image description here

Внутри моего component.ts я извлекаю содержимое Excel следующим образом:

var testUrl= "excel.xlsx";
var oReq = new XMLHttpRequest(); 
oReq.open("GET", testUrl, true); 
oReq.responseType = "arraybuffer";

oReq.onload = function(e) {
    var arraybuffer = oReq.response; 
    var data = new Uint8Array(arraybuffer);
    var arr = new Array();
    for(var i = 0; i != data.length; ++i){ 
            arr[i] = String.fromCharCode(data[i]);
    }
    var bstr = arr.join("");
    var workbook = XLSX.read(bstr, {type:"binary"});
    var first_sheet_name = workbook.SheetNames[0];
    var worksheet = workbook.Sheets[first_sheet_name]; 
    var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
    var jsonOut = JSON.stringify(json);
    console.log("test"+jsonOut);
}

oReq.onerror = function(e) {
    console.log(e);
}

oReq.send();

XLSX.utils.sheet_to_json отформатирует JSON следующим образом: enter image description here

Однако я бы хотел, чтобы JSON был следующим: enter image description here

Скорее всего, мне нужно было бы вручную создать JSON, но может ли кто-нибудь помочь мне указать направление, как я могу это сделать?

1 Ответ

0 голосов
/ 02 июля 2018

В вашем случае нам нужно изменить данные JSON, выполнив цикл над XLSX.utils.sheet_to_json объектом JSON:

// This object will contain the data in the format we want
var finalObj = { "object": []};

// Variables to track where to insert the data
var locIndex, firstCondIndex, secondCondIndex,
    lockey, firstCondKey, secondCondkey;

// We need to initialize all indexes to -1 so that on first time we can get 0, as arrays start with 0 in javascript
locIndex = -1;

// here obj is XLSX.utils.sheet_to_json
obj.object.map((value, index) => {
    // we don't want to consider name of columns which is first element of array
    if(!index) return;

    // Go inside only if not null
    if(value[0]) {
        // For Location
        finalObj.object.push(createObj(value[0]));
        locIndex++;
        // We also need to store key names to push it's children
        lockey = value[0];
        firstCondIndex = -1;
    }
    if(value[1]) {
        // For First Condition 
        finalObj.object[locIndex][lockey].push(createObj(value[1]));
        firstCondIndex++;
        firstCondKey = value[1];
        secondCondIndex = -1;
    }
    if(value[2]) {
        // For Second Condition
        finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey].push(createObj(value[2]));
        secondCondIndex++;
        secondCondkey = value[2];
    }
    if(value[3]) {
        // For Products
        // We just push the string
        finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey][secondCondIndex][secondCondkey].push(value[3]);
    }
});

function createObj(val) {
    // We need to initialize blank array so we can push the children of that element later on
    var obj = {};
    obj[val] = [];
    return obj;
}

console.log(finalObj);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...