How to Export Data to Excel in ReactJS

Introduction

 
In this article, we will learn how to export data in Excel using ReactJS. In this demo, we will use react-html-table-to-excel library to export data in an Excel sheet.
 
Prerequisites 
  • 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.
  1. npx create-react-app matform   
Open the newly created project in Visual Studio and install react-html-table-to-excel library using the following command.
  1. npm install --save react-html-table-to-excel  
Now install Bootstrap by using the following commands.  
  1. npm install --save bootstrap      
Now, open the index.js file and add import Bootstrap. 
  1. import 'bootstrap/dist/css/bootstrap.min.css';     
Now Install the Axios library by using the following command. Learn more about Axios 
  1. npm install --save axios     
Now go to the src folder and add a new component, named 'ExportExcel.js'.
 
Now open ExportExcel.js component and import following reference.
  1. import ReactHTMLTableToExcel from 'react-html-table-to-excel';  
 Add the following code in this component.
  1. import React, { Component } from 'react'  
  2. import axios from 'axios';  
  3. import ReactHTMLTableToExcel from 'react-html-table-to-excel';  
  4. export class ExportExcel extends Component {  
  5.         constructor(props) {  
  6.                 super(props)  
  7.                 this.state = {  
  8.                         ProductData: []  
  9.   
  10.                 }  
  11.         }  
  12.         componentDidMount() {  
  13.                 axios.get('http://localhost:51760/Api/Emp/employee').then(response => {  
  14.                         console.log(response.data);  
  15.                         this.setState({  
  16.                                 ProductData: response.data  
  17.                         });  
  18.                 });  
  19.         }  
  20.         render() {  
  21.                 return (  
  22.                         <div>  
  23.                                 <table id="emp" class="table">  
  24.                                         <thead>  
  25.                                                 <tr>  
  26.                                                         <th>Id</th>  
  27.                                                         <th>Name</th>  
  28.                                                         <th>Age</th>  
  29.                                                         <th>Address</th>  
  30.                                                         <th>City</th>  
  31.                                                         <th>ContactNum</th>  
  32.                                                         <th>Salary</th>  
  33.                                                         <th>Department</th>  
  34.   
  35.   
  36.   
  37.                                                 </tr>  
  38.                                         </thead>  
  39.                                         <tbody>              {  
  40.                                                 this.state.ProductData.map((p, index) => {  
  41.                                                         return <tr key={index}>  
  42.                                                                 <td>  
  43.                                                                         {p.Id}  
  44.                                                                 </td>  
  45.                                                                 <td >{p.Name}</td>  
  46.                                                                 <td >{p.Age}</td>  
  47.                                                                 <td >{p.Address}</td>  
  48.                                                                 <td >{p.City}</td>  
  49.                                                                 <td >{p.ContactNum}</td>  
  50.                                                                 <td >{p.Salary}</td>  
  51.                                                                 <td style={{ paddingRight: "114px" }} >{p.Department}</td>  
  52.                                                         </tr>  
  53.                                                 })  
  54.                                         }  
  55.   
  56.                                         </tbody>  
  57.   
  58.                                 </table>  
  59.                                 <div>  
  60.                                         <ReactHTMLTableToExcel  
  61.                                                 className="btn btn-info"  
  62.                                                 table="emp"  
  63.                                                 filename="ReportExcel"  
  64.                                                 sheet="Sheet"  
  65.                                                 buttonText="Export excel" />  
  66.                                 </div>  
  67.                         </div>  
  68.                 )  
  69.         }  
  70. }  
  71.   
  72. export default ExportExcel  
 Add a reference of this component in app.js file, add the following code in app.js file.
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import ExportExcel from './ExportExcel'  
  5.   
  6. function App() {  
  7.   return (  
  8.     <div className="App">  
  9.       <ExportExcel/>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. export default App;  
Our Reactjs 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".
  1. CREATE TABLE [dbo].[Employee](        
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,        
  3.     [Name] [varchar](50) NULL,        
  4.     [Age] [intNULL,        
  5.     [Address] [varchar](50) NULL,        
  6.     [City] [varchar](50) NULL,        
  7.     [ContactNum] [varchar](50) NULL,        
  8.     [Salary] [decimal](18, 0) NULL,        
  9.     [Department] [varchar](50) NULL,        
  10.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED         
  11. (        
  12.     [Id] ASC        
  13. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]        
  14. ON [PRIMARY]        
  15. GO       
Now add a demo data in this table.
 

Create a new Web API project

 
Open Visual Studio and create a new project.
 
How To Export Data To Excel In ReactJS
 
Change the name to MatUITable.
 
How To Export Data To Excel In ReactJS
 
Choose the template as Web API.
 
How To Export Data To Excel In ReactJS
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
How To Export Data To Excel In ReactJS
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
How To Export Data To Excel In ReactJS
 
Select EF Designer from the database and click the "Next" button.
 
How To Export Data To Excel In ReactJS
 
Add the connection properties and select database name on the next page and click OK.
 
How To Export Data To Excel In ReactJS
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click OK

How To Export Data To Excel In ReactJS
 
Now, our data model is successfully created.
 
Right-click on the Controllers folder and add a new controller. Name it as "Employee controller" and add the following namespace in the Employee controller.
  1. using MatUITable.Models;   
Now add a method to fetch data from the database.
  1. [HttpGet]    
  2. [Route("employee")]    
  3. public object Getrecord()    
  4. {    
  5.     var emp = DB.Employees.ToList();    
  6.     return emp;    
  7. }    
 Complete Employee controller code
  1. using System;      
  2. using System.Collections.Generic;      
  3. using System.Linq;      
  4. using System.Net;      
  5. using System.Net.Http;      
  6. using System.Web.Http;      
  7. using MatUITable.Models;      
  8. namespace MatUITable.Controllers      
  9. {      
  10.       
  11.     [RoutePrefix("Api/Emp")]      
  12.     public class EmployeeController : ApiController      
  13.     {      
  14.         EmployeeEntities DB = new EmployeeEntities();      
  15.         [HttpGet]      
  16.         [Route("employee")]      
  17.         public object Getrecord()      
  18.       
  19.         {      
  20.             var emp = DB.Employees.ToList();      
  21.             return emp;      
  22.         }      
  23.     }      
  24. }     
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
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");            
  2. config.EnableCors(cors);   
 Now go to visual studio code and run the project using 'npm start' command.
 
How To Export Data To Excel In ReactJS
 
Click on 'Export Excel' button. Once excel downloads, open and check.
 

Summary

 
In this article, we learned how we to Export data to an Excel sheet in ReactJS.