Simple Way To Export Data From API To Excel Using ReactJS in 2023
Tags: react, excel, tutorial, webdev
Published: 2023-02-17 05:31:31

### New React Project
```js
npx create-react-app react-to-excel
```

Start project
```js
npm start
```

Once project successfully created. Lets dive into installing necessary library.


### Library Installation

For this tutorial we will use library namely [SheetJS Community Edition] (https://docs.sheetjs.com/docs/). This library can installed through these package managers

**npm**
```js
npm i --save https://cdn.sheetjs.com/xlsx-0.19.2/xlsx-0.19.2.tgz
```

**pnpm**
```js
pnpm install https://cdn.sheetjs.com/xlsx-0.19.2/xlsx-0.19.2.tgz
```

**yarn**
```js
yarn add https://cdn.sheetjs.com/xlsx-0.19.2/xlsx-0.19.2.tgz
```

### User Interface

Let's make this kind of UI. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ouymkiiso9nfna2i35du.png)



**App.js**
```js
import "./App.css";

function App() {
  const handleDownload = () => {
    console.log("test button");
  };
  return (
    <div className="wrapper">
      <button onClick={handleDownload}>DOWNLOAD EXCEL</button>
    </div>
  );
}

export default App;

```

**App.css**
```css
.wrapper {
  padding: 20px;
}

button {
  margin-top: 20px;
  padding: 10px;
}
```

### Logic
First lets fetch data from API. In this tutorial I am using this API https://fakestoreapi.com/products. Lets add ``useState`` for storing data and ``useEffect`` for sending request after render.

**App.js**
```js
import { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch("https://fakestoreapi.com/products")
      .then((res) => res.json())
      .then((json) => setProducts(json));
  }, []);

  const handleDownload = () => {
    console.log("test data", products);
  };
  return (
    <div className="wrapper">
      <button onClick={handleDownload}>DOWNLOAD EXCEL</button>
    </div>
  );
}

export default App;
```

#### Result

![data to excel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kozgzut7zifsdl0xdb4i.png)

As you can see we successfully fetched data from API. Now lets implement logic for making our Excel file. First add ``import * as XLSX from "xlsx";`` on top of App.js file for importing SheetsJS library.

**App.js**
```js
import { useEffect, useState } from "react";
import "./App.css";
import * as XLSX from "xlsx";

function App() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch("https://fakestoreapi.com/products")
      .then((res) => res.json())
      .then((json) => setProducts(json));
  }, []);

  const handleDownload = () => {
    // flatten object like this {id: 1, title:'', category: ''};
    const rows = products.map((product) => ({
      id: product.id,
      title: product.title,
      category: product.category,
    }));

    // create workbook and worksheet
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(rows);

    XLSX.utils.book_append_sheet(workbook, worksheet, "Products");

    // customize header names
    XLSX.utils.sheet_add_aoa(worksheet, [
      ["Product ID", "Product Name", "Product Category"],
    ]);

    XLSX.writeFile(workbook, "ReportFor2023.xlsx", { compression: true });
  };
  return (
    <div className="wrapper">
      <button onClick={handleDownload}>DOWNLOAD EXCEL</button>
    </div>
  );
}

export default App;
```

#### Result 
As you can see from screenshot below by pressing to button. We can successfully download data from API inside Excel file.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kavh02c1ci5vi83bn1q6.png)


Now I open ReportFor2023.xlsx file 

![last demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yi523qb6pghap51zx464.png)

Project source code available on Github. [Source code] (https://github.com/jasurkurbanov/react-to-excel)

_If you need help for you project or doing any other web related projects reach me out_

_Email: jasurkurbanov96@gmail.com
Linkedin: https://www.linkedin.com/in/jasurkurbanov/_