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=

const header2=['Agent Name','DOB','City','Pincode'];
const field2=['agentName','dob','city','pincode'];
const report2Data=

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

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

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

//Logic Part
record1.unshift(["Customer  Report"].join(','));
record1.unshift(["  "].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


Popular Posts