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

sudhakar-sekar picture sudhakar-sekar  路  3Comments

nishthasb picture nishthasb  路  4Comments

Alex0007 picture Alex0007  路  3Comments

magtuan picture magtuan  路  3Comments

eyalcohen4 picture eyalcohen4  路  3Comments