How to Export Data to Excel in ReactJS
Join the DZone community and get the full member experience.Join For Free
In this article, we will learn how to export data in Excel using ReactJS. In this demo, we will use the react-html-table-to-excel library to export data in an Excel sheet.
- We should have basic knowledge of React.js and Web API.
- Visual Studio and Visual Studio Code IDE should be installed on your system.
- SQL Server Management Studio
- Basic knowledge of Bootstrap and HTML
Create ReactJS project
Now, let's first create a React application with the following command.
Open the newly created project in Visual Studio and install react-html-table-to-excel library using the following command.
Now install Bootstrap by using the following commands.
Now, open the index.js file and add import Bootstrap.
Now Install the Axios library by using the following command. Learn more about Axios here.
Now go to the src folder and add a new component, named "ExportExcel.js."
Now open ExportExcel.js component and import following reference.
Add the following code in this component.
Add a reference of this component in app.js file, add the following code in app.js file.
Our React.js project is created. Now create a database table and web API project to show data in a table.
Create a Table in The Database
Open SQL Server Management Studio, create a database named "Employee," and in this database, create a table. Give that table a name like "Employee."
Now add demo data in this table.
Create a New Web API Project
Open Visual Studio and create a new project.
Change the name to MatUITable.
Choose the template as "Web API."
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
Click on the "ADO.NET Entity Data Model" option and click "Add".
Select EF Designer from the database and click the "Next" button.
Add the connection properties and select database name on the next page and click OK.
Check the "Table" checkbox. The internal options will be selected by default. Now, click OK.
Now, our data model is successfully created.
Right-click on the Controllers folder and add a new controller. Name it "Employee controller" and add the following namespace in the Employee controller.
Now add a method to fetch data from the database.
Complete Employee controller code:
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines
Now go to Visual Studio Code and run the project using
npm start command.
Click on the "Export Excel" button. Once Excel downloads, open, and check.
Opinions expressed by DZone contributors are their own.