[Vuejs]-How to convert Object to csv file with a multiple sheet in excel/csv file by separating bullet of Object

0👍

You need to declare rows as object(rows = {}). When you looping you data array, use key name (deviceA,deviceB...) and declare array with key name that key name.

I have made the changes in your code and created code snippet.

See below screenshot and Code snippet

enter image description here

var data = {"deviceA":{"smokeSensor":[{"190501":{"0001":200,"0002":300}},{"190502":{"0001":20,"0002":30}}],"fireSensor":[{"190501":{"0001":700,"0002":750}},{"190502":{"0001":780,"0002":630}}]},"deviceB":{"smokeSensor":[{"190601":{"0001":100,"0002":110}},{"190602":{"0001":120,"0002":130}}],"fireSensor":[{"190601":{"0001":600,"0002":522}}]}};

const dataToCSV = data => {
    const rows = {};

    for (const device in data) {
        let keyName = device.replace(/^./, m => m.toUpperCase());
        rows[keyName] = [
            ["Date/Time", ...Object.keys(data[device])]
        ];
        const groups = {};
        let longest = 0;

        for (const sensor in data[device]) {
            for (const time of data[device][sensor]) {
                const k = Object.keys(time)[0];

                for (const hm in time[k]) {
                    const groupKey = `${k} ${hm.replace(/(\d\d)(\d\d)/, "$1:$2")}`;

                    if (!(groupKey in groups)) {
                        groups[groupKey] = [groupKey];
                    }

                    groups[groupKey].push("" + time[k][hm]);
                    longest = Math.max(longest, groups[groupKey].length);
                }
            }
        }

        for (const group of Object.values(groups)) {
            while (group.length < longest) {
                group.push("");
            }

            rows[keyName].push(group);
        }
    }

    return rows;
}

const rowObject = dataToCSV(data);

function exportToCSV(rows, keyName) {
    let csvContent = ""
    rows.forEach(function(rowArray) {
        let row = rowArray.join(",")
        csvContent += row + "\r\n"
    });
    var blob = new Blob([csvContent], {
        type: "xls/xlsx"
    });
    var url = window.URL.createObjectURL(blob);
    $('#container').append(`<a download="${keyName}.csv"  href="${url}">Click to Download : ${keyName}</a>`);
}
for (let key in rowObject) {
    exportToCSV(rowObject[key], key);
}
#container a{
    display: inline-block;
    width: 100%;
    background-color: #3c3c3c;
    color: #fff;
    padding: 10px 20px;
    margin: 5px 0px;
    text-decoration: none;
}

#container a:hover{
  color:#ffa;
  text-decoration: underline; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container"></div>

Leave a comment