How to Export Data to Excel in ReactJS
Join the DZone community and get the full member experience.
Join For FreeIntroduction
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.
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.
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.
npm install --save react-html-table-to-excel
Now install Bootstrap by using the following commands.
xxxxxxxxxx
npm install --save bootstrap
Now, open the index.js file and add import Bootstrap.
xxxxxxxxxx
import 'bootstrap/dist/css/bootstrap.min.css';
Now Install the Axios library by using the following command. Learn more about Axios here.
xxxxxxxxxx
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.
xxxxxxxxxx
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
Add the following code in this component.
xxxxxxxxxx
import React, { Component } from 'react'
import axios from 'axios';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
export class ExportExcel extends Component {
constructor(props) {
super(props)
this.state = {
ProductData: []
}
}
componentDidMount() {
axios.get('http://localhost:51760/Api/Emp/employee').then(response => {
console.log(response.data);
this.setState({
ProductData: response.data
});
});
}
render() {
return (
<div>
<table id="emp" class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>City</th>
<th>ContactNum</th>
<th>Salary</th>
<th>Department</th>
</tr>
</thead>
<tbody> {
this.state.ProductData.map((p, index) => {
return <tr key={index}>
<td>
{p.Id}
</td>
<td >{p.Name}</td>
<td >{p.Age}</td>
<td >{p.Address}</td>
<td >{p.City}</td>
<td >{p.ContactNum}</td>
<td >{p.Salary}</td>
<td style={{ paddingRight: "114px" }} >{p.Department}</td>
</tr>
})
}
</tbody>
</table>
<div>
<ReactHTMLTableToExcel
className="btn btn-info"
table="emp"
filename="ReportExcel"
sheet="Sheet"
buttonText="Export excel" />
</div>
</div>
)
}
}
export default ExportExcel
Add a reference of this component in app.js file, add the following code in app.js file.
xxxxxxxxxx
import React from 'react';
import logo from './logo.svg';
import './App.css';
import ExportExcel from './ExportExcel'
function App() {
return (
<div className="App">
<ExportExcel/>
</div>
);
}
export default App;
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."
xxxxxxxxxx
CREATE TABLE [dbo].[Employee](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Age] [int] NULL,
[Address] [varchar](50) NULL,
[City] [varchar](50) NULL,
[ContactNum] [varchar](50) NULL,
[Salary] [decimal](18, 0) NULL,
[Department] [varchar](50) NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
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.
xxxxxxxxxx
using MatUITable.Models;
Now add a method to fetch data from the database.
xxxxxxxxxx
[HttpGet]
[Route("employee")]
public object Getrecord()
{
var emp = DB.Employees.ToList();
return emp;
}
Complete Employee controller code:
xxxxxxxxxx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MatUITable.Models;
namespace MatUITable.Controllers
{
[RoutePrefix("Api/Emp")]
public class EmployeeController : ApiController
{
EmployeeEntities DB = new EmployeeEntities();
[HttpGet]
[Route("employee")]
public object Getrecord()
{
var emp = DB.Employees.ToList();
return emp;
}
}
}
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
xxxxxxxxxx
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
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.
Further Reading
Opinions expressed by DZone contributors are their own.
Comments