Exporting to CSV

export your json object to csv

Thu, 20 Oct 2022

This is a client side function I made to create a csv and download it without using any external packages

export const exportToCSV = (data, title) => {
  const csvContent = `data:text/csv;charset=utf-8,${data
    .map(e => e.join(","))
    .join("\n")}`;
  const encodedUri = encodeURI(csvContent);
  const link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", `${title}.csv`);
  document.body.appendChild(link); // Required for FF

  link.click();
};

This takes in an array data and a title for the file

Your data array should be in the format

const data = [
  [], //headers go here
  ...restOfYourData
];

If you don’t want headers you can skip it and just create an array for each row in your csv. Example

const data = [
  ["Name", "Age"]
  ["Bob", "6"],
  ["Jill", "12"]
]

This will create a csv like this

“Name”, “Age”, “Bob”, “6”, “Jill”, “12”

Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge