Create a multi column csv report in nodejs without external library.


Recently I had a requirement to create a CSV report with multiple columns(merging two or more reports) in a single CSV file, but I didn't find any particular library(Maybe I didn't search properly) but found this solution. 

So let's begin with code that is self-explanatory.

const fs = require('fs');
const _file = `Agent_Customer_Report.csv`

//Report 1
const header1=['Customer Name','DOB','City','Pincode'];
const field1=['custName','dob','city','pincode'];
const report1Data=
[{'custName':"ABHISHEK",'dob':'01/23/1992','pincode':'443221','city':"Mumbai"}{'custName':"PUNIT",'dob':'01/23/1992','pincode':'443221','city':"Mumbai"}]

//Report2
const header2=['Agent Name','DOB','City','Pincode'];
const field2=['agentName','dob','city','pincode'];
const report2Data=
[{'agentName':"AGENT001",'dob':'01/23/1992','pincode':'443221','city':"Mumbai"},
{'agentName':"AGENT002",'dob':'01/23/1992','pincode':'443221','city':"Mumbai"}]

const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here

let record1 = report1Data.map(row => field1.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));

let record2 = report2Data.map(row => field2.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));

//Logic Part
record1.unshift(header1.join(','));
record1.unshift(["Customer  Report"].join(','));
record1.unshift(["  "].join(','));
record1.unshift(record2.join('\r\n'));
record1.unshift(header2.join(','));
record1.unshift(["Agent  Report"].join(','));

let csvArray = record1.join('\r\n');

fs.writeFileSync(_file, csvArray)
In this way, you can add more such headers and can merge many reports into a single csv.

I hope you like this article. Please stay connected for more such articles.

You can also follow me on Twitter or Linkedin for the latest updates.

Written By:

Saurabh Joshi


Comments

Popular Posts