Exporting Arrays to Excel: A Reusable React Component
As a developer, you’ve likely encountered the need to export arrays of objects to Excel files. This common feature request is especially prevalent in admin dashboard projects. In this article, we’ll explore the fundamental concepts involved in exporting arrays to Excel sheets and create a reusable React component using Chakra UI.
Understanding the Requirements
To create a reusable export-array-to-excel button, we need to fulfill the following criteria:
- The component should be reusable and importable into any page.
- When clicked, it should open a modal allowing users to choose between downloading all columns or selected columns.
- The modal should contain a download button that downloads a JSON API response array directly into a spreadsheet file based on the selected columns.
Setting Up the React App and Chakra UI
To get started, we’ll set up a demo React app using Create React App and install Chakra UI. Chakra UI is an open-source component library that provides simple, modular, and accessible components for building UI elements.
Converting Arrays to Excel
To convert an array of objects to an Excel file, we’ll perform four tasks:
- Get the API response array and convert it to a table: We’ll loop through the keys of the first object to form the table headers and then loop through each object to create rows.
- Embed the table into a spreadsheet XML template: We’ll use the SpreadsheetDataXML specification by Microsoft to describe how a spreadsheet file should be structured.
- Programmatically create a file URL for the spreadsheet template: We’ll convert the Excel template into a file or file-like object using the blob method and create a unique file URL using the createObjectURL method.
- Assign the created URL to the href of an anchor tag with a download attribute: We’ll programmatically click the anchor tag to prompt a download.
Creating the Reusable Export-Array-to-Excel Component
We’ll create two files: ArrayToExcel.js
and ArrayToExcelButton.js
. The former will contain the function that takes care of the conversion and download, while the latter will house the button, modal, and other necessary UI elements.
Assembling UI Elements with Chakra UI
We’ll import the necessary UI elements from Chakra UI and create a button, modal, select input, and checkbox. When the main button is clicked, it will open up a modal that lets users choose between downloading all columns or selected columns.
Testing the Component
We’ll make a mock API fetch call in App.js
and pass userData
into the ArrayToExcelButton
component as props. With that, our export-array-to-excel component is ready!
Conclusion
You’ve now learned how to export an array of objects to an Excel file using a reusable React component. This feature request is common in admin dashboard projects, and with this knowledge, you’re ready to build something great!