Exporting Data to Excel in React Using xlsx: A Step-by-Step Guide

Excel spreadsheets are a powerful tool for organizing and analyzing data. In many web applications, there's often a need to export data into Excel format for further analysis or sharing with others. In this tutorial, we'll explore how to export data to an Excel file in a React application using the xlsx library.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • Node.js and npm installed on your machine.

  • A basic understanding of React.

Setting Up Your React Project

If you haven't already set up a React project, you can do so using create-react-app or any other method you prefer. For this tutorial, we'll assume you have a working React application.

We will break down the code step-by-step:

Step 1: Installing the xlsx Library

To work with Excel files in a React application, we'll need the xlsx library. You can install it using npm:

npm install xlsx

Step 2: Chat or other Data

I am using dummy data here as an example, you can get data from the backend or create your own data.

Step 3: Onclick Event

return (
    <div>
       <button onClick={createExcel}>Download Excel</button>
    </div>
  );

Here we are creating a simple button, with an onClick event. When a user clicks on a button the onClick event is triggered and it will call the createExcel function.

Step 4: The createExcel Function:

This function is the heart of our code. It's responsible for creating the Excel document from the chat data. All logic for the code we are applying here:

const createExcel = async () => {
}

Here starts the main logic of the code:

Step 5: Create a new Workbook

Inside the function, we create a new Excel workbook using XLSX.utils.book_new(). This workbook will serve as a container for our Excel data. Workbook in the sense new Excel file where we are going to put all the data.

 const workbook = XLSX.utils.book_new();

Step 6: Get the specific data you want in the Excel

If you want to export only specific fields from the chatMessages data, you can use the map function to extract and transform the data as needed. For example, you can create a new array called extractedData that includes only the user and message fields. However, in the provided code, we export the entire chatMessages dataset as is.

  const extractedData = chatMessages.map(({ name, langauge }) => ({ name, langauge }));

Step 7: Create a new worksheet

Next, create a new worksheet within the workbook using XLSX.utils.json_to_sheet(). This function converts our JSON data (in this case, chatMessages) into a format that Excel can understand.

// In case specific data:   
// const worksheet = XLSX.utils.json_to_sheet(extractedData);
       const worksheet = XLSX.utils.json_to_sheet(chatMessages);

Step 8: Add the worksheet to the workbook

After extracting data in the worksheet, in the next step, we have to add that specific worksheet in the workbook, specifying the name of the worksheet. Here I am naming the worksheet as 'Excel Data'.

XLSX.utils.book_append_sheet(workbook, worksheet, 'Excel Data');

Step 9: Create a Blob from the workbook data

In the next step use XLSX.writeFile to convert the workbook into a Blob object and specify the filename as 'data.xlsx'. The Blob object is a binary representation of our Excel file.

const blob = XLSX.writeFile(workbook, 'data.xlsx');

Then, create a temporary <a> element in the DOM. This element will act as a link for downloading the Excel file. Then set the download attribute of the link to 'data.xlsx', which specifies the filename for the downloaded file. To hide the link use style.display property to 'none'. This ensures that the link won't be visible to users.

const link = document.createElement('a'); 
  link.download = 'data.xlsx'; 
  link.style.display = 'none';

Add the temporary link to the DOM by appending it to the <body> element. This step is necessary for the link to be programmatically clickable. Now that the link is in the DOM, we have to programmatically trigger a click event on it. This action simulates a user clicking a link, which initiates the download process.

document.body.appendChild(link); 
 link.click();

Finally, after the download is initiated, we remove the temporary link from the DOM. This cleanup step ensures that the link does not clutter the page.

document.body.removeChild(link);

In summary, the createExcel function creates an Excel workbook, adds a worksheet with your data to it, converts the workbook into a Blob for download, and then uses a hidden link to trigger the download process. Once the download is complete, the temporary link is removed from the DOM. This entire process allows you to export your chatMessages data as an Excel file when the "Download Excel" button is clicked.

Conclusion

In this tutorial, we've learned how to export data to an Excel file in a React application using the xlsx library. You can now use this knowledge to enhance your web applications by providing users with the ability to export data to Excel format.

Feel free to customize the DownloadExcel component to suit your application's needs, such as modifying the data source or file name. Excel export functionality can be a valuable addition to various types of web applications, including dashboards, reporting tools, and data-driven applications.

Now, go ahead and implement Excel export in your React project and empower your users to work with their data more effectively!

I hope you found this tutorial helpful. My next blog will be on how to convert data into pdf format, which requires little more logic. If you have any questions or want to share your experience, please leave a comment below. Happy coding!

Code Repository:

You can access the complete source code for this tutorial on my GitHub repository by visiting the following link: GitHub Repository

Feel free to explore the code, use it in your projects, or contribute to its development. If you have ideas for adding more features, improvements, or enhancements, I welcome your contributions. Please don't hesitate to create pull requests, report issues, or provide suggestions through the repository's issue tracker.

Your contributions are highly valued and can help make this project even better. Thank you for being a part of the community!

3
Subscribe to my newsletter

Read articles from Pranjali Sankpal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pranjali Sankpal
Pranjali Sankpal