How to download an xlsx file in React.js?

Member

by brandy , in category: Javascript , a year ago

How to download an xlsx file in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 10 months ago

@brandy 

In order to download an XLSX file in React.js, you can make use of the FileSaver.js library. Here are the steps to achieve this:

  1. Install the FileSaver.js library by running the following npm command:
1
npm install file-saver


  1. Import the FileSaver.js library in your React component:
1
import { saveAs } from 'file-saver';


  1. Create a function to handle the XLSX file download. This function should create a new Blob with the XLSX file content and use FileSaver.js to save it:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const downloadXlsxFile = () => {
  // Replace with your XLSX file content
  const xlsxFileContent = 'your-xlsx-file-content';

  // Create a new Blob with the XLSX file content
  const blob = new Blob([xlsxFileContent], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

  // Use FileSaver.js to save the Blob
  saveAs(blob, 'your-xlsx-file-name.xlsx');
}


  1. Add a button or any other element in your React component that triggers the downloadXlsxFile function when clicked:
1
<button onClick={downloadXlsxFile}>Download XLSX File</button>


Now, when you click the button, it will download the XLSX file with the specified name.


Note: You need to replace 'your-xlsx-file-content' with the actual content of your XLSX file, and 'your-xlsx-file-name' with the desired name for the downloaded file.