How To Export Data To Excel From Api Using React
CREATE AND INSTALL
Create new react project
npx create-react-app react-data-to-excel
Now start project
npm start
Once project successfully created.
Lets dive into installing necessary libraries for our project. Install these three libraries.
npm install xlsx file-saver axios --save-dev
👉xlsx — library for parsing and writing various spreadsheet formats
👉file-saver — library for saving files on the client-side
👉axios — promise based HTTP client for the browser and node.js. We will use it for fetching data from server
UI AND LOGIC
Create a component namely ExportToExcel.js
import React from 'react'
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
export const ExportToExcel = ({ apiData, fileName }) => {
const fileType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const fileExtension = ".xlsx";
const exportToCSV = (apiData, fileName) => {
const ws = XLSX.utils.json_to_sheet(apiData);
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
return (
<button onClick={(e) => exportToCSV(apiData, fileName)}>Export</button>
);
};
Sample data we will get from https://jsonplaceholder.typicode.com/posts
App.js
import React from 'react'
import axios from 'axios'
import './App.css';
import {ExportToExcel} from './ExportToExcel'
function App() {
const [data, setData] = React.useState([])
const fileName = "myfile"; // here enter filename for your excel file
React.useEffect(() => {
const fetchData = () =>{
axios.get('https://jsonplaceholder.typicode.com/posts').then(r => setData(r.data) )
}
fetchData()
}, [])
return (
<div className="App">
<ExportToExcel apiData={data} fileName={fileName} />
</div>
);
}
export default App;
Start project
npm start
Once it successfully started. You can see one button. By pressing this button you download excel file with data filled from https://jsonplaceholder.typicode.com/posts
Github repo for this project link
Originally published on dev.to