Logo
Published on

How to Export Data in CSV Format with React

Authors

Photo by Christopher Gower on Unsplash

In this article, I'll teach you how to export data in CSV format in ReactJS in the simplest possible way. When you need to download Report from a API response, and need to save it in csv format. So let's see how we may accomplish it in the most efficient and straightforward possible way.

  1. So, to download a CSV file, we'll start by creating a simple HTML download button using MUI. Copy and paste the code below into your app.js file.
<Button
  sx={{ height: '36px', fontSize: '12px', marginTop: '10px' }}
  onClick={handleDownloadReports}
  variant="contained"
>
  Download Report
</Button>
  1. In order to download the response from API. let create axios Instance that can we used to make and API calls in your entire project. Copy and paste the code below into your utils.js file.
export const getAuthorizationHeader = () => `Bearer ${Token}`

// import axios from 'axios'

export const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    Authorization: getAuthorizationHeader(),
  },
})
  1. Now lets make an API call to get the response which need to be downloaded in CSV format so you can use the axios Instance to make a api call that you have added in step 2 and using Blob you can generate the report for the response that you have recieved.
const handleDownloadReports = () => {
  const url = 'baseurl for download'
  axiosInstance(url, {
    headers: { Authorization: getAuthorizationHeader() },
  })
    .then((response) => {
      console.log('response', response)
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      const fileName = `downloaded Report ${moment(new Date()).format('DD MMM YY')}.csv`
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      link.remove()
    })
    .catch((error) => {
      console.log(error)
    })
    .finally(() => {
      // setTableLoading(false)
    })
}

This is how the report will be generated and the file will get downloaded. Based on column field which were added in api response will gets populated in the report sheet.

Output: