How To Export Data To Excel From Api Using ReactJS (incl. Custom Headers)
Tags: react, javascript, excel, api
Published: 2022-05-20 10:48:52

> In my [previous post](https://dev.to/jasurkurbanovinit/how-to-export-data-to-excel-from-api-using-react-25go), about exporting data to Excel from api using React, there were comments like how to add custom header and style to the sheet!?. So considering these comments, in this post I decided to show solution for first issue which is adding custom headers to your Excel sheet.

In this post two ways of adding custom headers will be shown

# First way
## Setup
### Create a new project
```js
npx create-react-app react-data-to-excel
```

### Run project locally
```js
npm start
```

![How To Export Data To Excel From Api Using React (incl. Custom Headers)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ek3q4fumb0j07655fve.png)


Let's dive into next step.

## Install libraries
For this project we need to install following libraries:

```js
npm install xlsx file-saver axios
```

**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_

## Components
Inside your project create component `ExportToExcel.js`
```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>
  );
};
```

Update your `App.js`

```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(postData => {
     
     // reshaping the array
     const customHeadings = postData.data.map(item=>({
       "Article Id": item.id,
       "Article Title": item.title
     }))

      setData(customHeadings) 
     })
    }
    fetchData()
  }, [])

  return (
    <div className="App">
      <ExportToExcel apiData={data} fileName={fileName} />
    </div>
  );
}

export default App;
```

According to [official SheetJS CE docs](https://docs.sheetjs.com/docs/example). By default, `json_to_sheet` creates a worksheet with a header row. 

This way of adding header is reshaping array to object, based on our needs. Since the headers for Excel file come from the object keys we defined. 

In our case headers will be "Article Id" and "Article Title".


### Run project
```js
npm start
```

![How To Export Data To Excel From Api Using React (incl. Custom Headers) ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hrcayu1t6jrw0txk7kd.png)

Once project started successfully, click to button to download Excel file.

![How To Export Data To Excel From Api Using React (incl. Custom Headers) ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3hpjl0uf9bn5an2agp4.png)
  

### Result
![How To Export Data To Excel From Api Using React (incl. Custom Headers) ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbg6d66uwi815gysop37.png)
 

# Second way
No need to reshape array inside `App.js`. Just need to add this code 
```bash
 XLSX.utils.sheet_add_aoa(ws, [["Name", "Birthday", "Age", "City"]], { origin: "A1" });
```
inside your `ExportToExcel.js` file
```js
  const exportToCSV = (apiData, fileName) => {
    const ws = XLSX.utils.json_to_sheet(apiData);
    /* custom headers */
    XLSX.utils.sheet_add_aoa(ws, [["Name", "Birthday", "Age", "City"]], { origin: "A1" });
    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);
  };
```

### Result
![How To Export Data To Excel From Api Using React (incl. Custom Headers)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3auq08udmet8kt5i9nq.png)
 
 

### Source code links
[1st way](https://github.com/jasurkurbanovinit/react-api-data-to-excel)

[2nd way](https://github.com/jasurkurbanovinit/react-api-data-to-excel-2nd)