Excel Downloads in React: Simplifying User Experience

Semih Celik
2 min readJan 5, 2024

--

Photo by Rubaitul Azad on Unsplash

Are you ready to explore practical ways to quickly download Excel files in your React project? This short guide provides tips for simplifying user experience and optimizing data sharing. Discover fast and effective steps to enhance interaction in your React application. Let’s get started!

  1. Open your project directory in the terminal and add the necessary dependency for handling Excel files. Execute the following command:
npm i file-saver

npm i xlsx

2. Create a simple function to download the Excel file. Open a new file, for example, ExcelDownload.js, and add an Excel download function as shown below:

import { saveAs } from "file-saver";
import * as XLSX from 'xlsx';

export const ExcelDownload= (data, columns, filename) => {

// Convert the data to a format compatible with Excel
const excelData = [
columns.map((column) => column.title),
...data.map((item) => columns.map((column) => item[column.dataKey])),
];

// Create the Excel file
const worksheet = XLSX.utils.aoa_to_sheet(excelData);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet 1");

// Download file
const excelBuffer = XLSX.write(workbook, { bookType: "xlsx", type: "array" });
const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, `${filename}.xlsx`);
};


// Example of Usage:
// const yourData = [
// { column1: "Data 1", column2: "Data 2" },
// // ... Other data
// ];

// const columns = [
// { title: "Column 1", dataKey: "column1" },
// { title: "Column 2", dataKey: "column2" },
// // ... Other columns
// ];

// ExcelDownload(yourData, columns, "exported_data");
Photo by Lautaro Andreani on Unsplash

Utilize this component by incorporating it into your application wherever necessary. Simply import the ExcelDownload function in the desired file, and by calling it with the appropriate data and configurations, you can seamlessly integrate Excel file downloads into different sections of your application. This provides a flexible and modular solution for managing Excel files according to your project’s requirements.

--

--