Sheetjs: Control sequence of excel output

Created on 19 Jul 2017  路  3Comments  路  Source: SheetJS/sheetjs

We are using js-xlsx to generate excel from json object.

ws = XLSX.utils.json_to_sheet(newJsonObj);
...
wb.SheetNames.push(fname);
wb.Sheets[fname] = ws;
var wbout = XLSX.write(wb, wopts);

But, the output spreadsheet columns are not as expected.
Any suggestion?

Thanks ahead

Most helpful comment

The json_to_sheet function takes an options argument, set the header key to an array with the desired order. For example, using the CSV output to show the actual order:

// by default generates 'a,b,c\n1,2,3\n'
XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet([{a:1,b:2,c:3}]))

// pass header:['c','a','b'] to reorder: 'c,a,b\n3,1,2\n'
XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet([{a:1,b:2,c:3}], {header:['c','a','b']}))

// pass header:['c','b','a'] to reorder: 'c,b,a\n3,2,1\n'
XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet([{a:1,b:2,c:3}], {header:['c','b','a']}))

All 3 comments

Can you share the original object and what you expected?

We define a object as follows:
var subOb = {
subscriber: {
// sys_id: ag.getValue('subscriber'),
number: ag.subscriber.subr_num + '',
name: ag.subscriber.ref_name + '',
account: {
number: ag.subscriber.cust_num + ''
}
},
total: {
used_days: Number(ag.getAggregate('SUM', 'drdp_days')),
total_charges: Number(ag.getAggregate('SUM', 'drdp_charges')),
data_usage: Number(ag.getAggregate('SUM', 'drdp_data_volume'))
},
countries: {}
};

    Then,

...
var expOb = JSON.parse(JSON.stringify(subOb));
....

    exportData.push(flatten(expOb));

And, expect the excel out in with column in same order as the object.
However, the columns of the output excel are in random order.....but the rows are in proper sequece.

The json_to_sheet function takes an options argument, set the header key to an array with the desired order. For example, using the CSV output to show the actual order:

// by default generates 'a,b,c\n1,2,3\n'
XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet([{a:1,b:2,c:3}]))

// pass header:['c','a','b'] to reorder: 'c,a,b\n3,1,2\n'
XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet([{a:1,b:2,c:3}], {header:['c','a','b']}))

// pass header:['c','b','a'] to reorder: 'c,b,a\n3,2,1\n'
XLSX.utils.sheet_to_csv(XLSX.utils.json_to_sheet([{a:1,b:2,c:3}], {header:['c','b','a']}))
Was this page helpful?
0 / 5 - 0 ratings

Related issues

dullin picture dullin  路  3Comments

seanmcilvenna picture seanmcilvenna  路  3Comments

goxr3plus picture goxr3plus  路  3Comments

upasana-shah picture upasana-shah  路  4Comments

thomasledoux1 picture thomasledoux1  路  3Comments