Export data as CSV client-side using Papaparse

Many web apps allow users to export data as CSV. This can be done using JavaScript on the browser. Papaparse is a nice package that prepares the CSV for us. This blog post has the code to show you how to do this.

Prepare CSV using Papaparse

The first step is to install Papaparse.

yarn add papaparse 

Add an import statement at the top of your module.

import Papa from 'papaparse';

Let’s assume that we are exporting an array of items from a table. We convert the array of objects into an array of array. The code below shows you how.

const data = objects.map(obj => [
        obj.id,
        obj.title,
        obj.description
    ]);

Optionally, it is possible to create a header row in the CSV file.

const fields = ['ID', 'Title', 'Description'];

Use Papaparse to create the CSV.

const csv = Papa.unparse({
        data,
        fields
    });

Download the CSV

With the CSV created, it is time to write some code to download the CSV.

Convert the CSV into a JS blob.

const blob = new Blob([csv]);

Create a hyperlink tag with the blob. URL has an utility function, createObjectURL that sets the href attribute of the hyperlink.

const a = document.createElement('a');
a.href = URL.createObjectURL(blob, { type: 'text/plain' });

Set the name of the file using the download attribute.

a.download = 'CSV Export File';

Click on the hyperlink programmatically. For this, we need to add the hyperlink tag to the DOM, simulate the click event, and remove the hyperlink tag from the DOM.

document.body.appendChild(a);
a.click();
document.body.removeChild(a);

With Papaparse and some utility code, we are able to export data as a CSV file using JavaScript.

Related Posts

One thought on “Export data as CSV client-side using Papaparse

  1. URL.createObjectURL expects only one argument. It should look like the following:

    const blob = new Blob([csv], { type: ‘text/csv’ })

    const a = document.createElement(‘a’);
    a.href = URL.createObjectURL(blob);

Leave a Reply

Your email address will not be published.