In this article, you can learn how to export an array of objects to an Excel file using a reusable React component.

Not so long ago, I was tasked with adding an export-array-to-excel button to some pages of a React application. The criteria given for this button was:

  • It had to be reusable, so it can be imported into any page and used as needed
  • When clicked, it should open up a modal that lets users choose between downloading all columns (all properties from each individual object of the array) or selected columns (only selected properties from individual objects of the array)
  • The modal should contain a download button that will download a JSON API response array directly into a spreadsheet file based on the columns selected

A Screenshot of the export-array-to-excel Component

A screenshot of the export-array-to-excel component.

I found out that this is a common feature request (maybe with a little variation) given to developers, especially those who work on admin dashboard-like projects, and that is why I’m writing this article.

This article assumes that you have a fair knowledge of JavaScript and React. In this article, I will first show you the fundamental concepts involved in exporting an array of objects into an Excel sheet. Then, based on that, create the reusable export-array-to-excel component shown above, using Chakra UI as the component library of choice.

The first thing that needs to be figured out is how to prompt a download on the browser.

In plain HTML, creating a button to prompt a download in the browser is pretty straightforward using an anchor tag and its download attribute. Simply pass the URL or file path of the file to be downloaded to the href attribute:

<a href="/files/excel-sheet-to-download.xls" download=”customer-list”>
       <button> Download to excel </button>
</a>

The download attribute is part of the HTML5 spec, and it specifies that the target should be downloaded when the link is clicked. The value passed to the download attribute specifies the filename for the downloaded file.

Unfortunately, the solution above won’t exactly work for our use case because there isn’t a pre-existing Excel file to link to.

We’ll have to perform four tasks spontaneously when the download button is clicked:

  1. Get the API response array and convert it to a table
  2. Embed the table into a spreadsheet XML template
  3. Programmatically create a file URL for the spreadsheet template using the Blob and URL.createObjectURL() methods
  4. Finally, assign the created URL to the href of an anchor tag with a download attribute, then programmatically click the anchor tag to prompt a download

Let’s go over each step and write the necessary code for it. But first, we need to set up a React app and Chakra UI.

#react #excel #javascript #web-development

Build a Reusable React Component to Export Arrays to Excel
2.60 GEEK