简体   繁体   中英

How to write to excel file using XLSX while keeping the same order

Here is my code that writes to the sheet.

const handleClick = () => {
    var wb = XLSX.utils.book_new();
    var ws = XLSX.utils.json_to_sheet(arrayofobjects);
    XLSX.utils.book_append_sheet(wb, ws, 'Test');
    XLSX.writeFile(wb, 'file.xlsx');
};

let arrayofobjects = [
    {
        "00": 4,
        "01": 6,
        "10": 12,
        "11": 7,
    },
    {
        "00": 7,
        "01": 7,
        "10": 4,
        "11": 5,
    }
]

But I am getting output in another order in excel

首先我得到 10,11 后来我得到 00,01

This is what I am expecting

在此处输入图像描述

What you are missing is a header array in the desired order.

for instance

// defined array of your headers
const header = ["00", "01", "10", "11"]

// create workbook as usual
const wb = XLSX.utils.book_new();

// here you pass an additional variable called header
const ws = XLSX.utils.json_to_sheet(
    arrayofobjects,
    {header:header}, //you can also use {header} but for simplicity's sake i left it as is
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM