Search code examples
node.jsxlsxexceljsjson2xls

How to change the position of header columns of excel file using NodeJS


I have a dynamic JSON data fro which I am creating a Excel file using jsno2xls library nut here the resulting excel file header are like Year,DOB,Name and Age and I want excel data in this format Name,Age,DOB and Year.Is there any way I can perform this action and get data in desired format.

Below is what I am doing to create Excel sheet.

const parsedData = [{},....,{}];
const xls = json2xls(parsedData);
fs.writeFileSync('datasheet.xlsx', xls, 'binary');    

Here in above code parsedData is coming from database which can have any number of fields in JSON object.

But in resulting Excel file I always want Name and Age column at first.


Solution

  • Try providing options object, where you set fields property to an array of fields you want to export, which will also export them in that order:

    const xls = json2xls(parsedData, {
        fields: ['Name', 'Age', 'DOB', 'Year']
    });
    

    If keys don't correspond (not case sensitive), then try transforming the data, where you'll create a new object whose keys correspond to those you want in the xlsx file:

    const parsedData = [{
        dob: "dob",
        name: 'bar',
        age: 'moo',
        year: new Date()
    }];    
    
    const transformedJson = parsedData.map(obj => {
    
        const newObject = {};
    
        newObject['D O B'] = obj['dob'];
        newObject['Name'] = obj['name'];
        newObject['Age'] = obj['age'];
        newObject['Year'] = obj['year'];
    
        return newObject;
    
    });   
     
    var xls = json2xls(transformedJson, {
        fields: ['Name', 'Age', 'D O B', 'Year']
    });
    
    fs.writeFileSync('data.xlsx', xls, 'binary');