How To Export Data Tables as CSV and Excel Files in React

How To Export Data Tables as CSV and Excel Files in React

Ever worked with table data in your React application and wanted to include a file export functionality?

Recently, I was to implement a feature that required exporting some user data displayed in a table, as .csv and Excel files.

I had initially thought it was to be handled on the backend and the response (returned as a file) can be downloaded. However, there was a miscommunication and I ended up working on a frontend implementation.

It was eventually handled from BE btw.

I had to explore different resources, so I figured compiling all the steps into one article would be useful to anyone else that might be searching for a similar solution.

Or even myself in the future.

In this post, you will learn how to export React tables from the frontend, in formats like .csv, .xls and .xlsx. You will also be able to define specific columns to export.

No backend functionality required (apart from fetching the table data, of course!)

What you need

  • An already set-up React project
  • Your Table component already populated with data

What we will use

react-csv is a good choice for React projects and you can use XLSX on both frontend and backend.

There are several other package options to try, especially for the .csv format. In my opinion, it’s best to carefully select packages you use in your projects. Choose packages that are regularly maintained, have good functionalities, large usage rate, and most importantly, fit your use case.

P.S You should go through the documentation of the two packages to get a better understanding of other available functionalities that you might need.

Steps

  • Import what you need from both packages
import {CSVLink} from 'react-csv'
import {utils, writeFile} from 'xlsx'
  • Define the columns in your data you want to export
const fileColumns = ['Name', 'Email', 'Phone Number', 'Age']
  • Prepare data to be exported
const [exportData, setExportData] = useState([fileColumns])

useEffect(() => {
    setExportData([fileColumns]) //always ensure exportData initially contains the fileColumns only
    if (isFetched) { //variable for checking if tableData is available
      tableData?.forEach((item) => {
        setExportData((data: any) => [
          ...data,
          [
            item.name,
            item.email,
            item.phone_number,
            item.age,
          ],
        ])
      })
    }
}, [tableData, isFetched])

The CSVLink component downloads the data props with the specified filename, when clicked. That's why our data is being prepared ahead.

If your tableData will not be changing, you can get rid of the dependency array (leave it empty).

  • Logic for exporting as Excel
const exportAsExcel = () => {
    let wb = utils.book_new()
    let ws = utils.json_to_sheet(exportData)
    utils.book_append_sheet(wb, ws, `users_data`)
    writeFile(wb, `users_data.xlsx`)
  }
  • Add buttons for export (use your own styles)
<div className='flex justify-between items-center'>
    <CSVLink
         data={exportData}
         filename={`users_data.csv`}
         className='btn custom-bg me-2'
         target='_blank'
    >
        Export as CSV
   </CSVLink>

   <div className='btn btn-light' onClick={exportAsExcel}>
       Export as Excel
   </div>
</div>

Notes:

  • You can specify a separate headers props for the CSVLink component, instead of populating exportData with the fileColumns as initial value.
  • You can also add an onClick props to define extra click handling logic.
  • react-csv also works with .xls, so you can name your file as such, if you still use this extension for your Excel files.

Again, the documentation provides several other options you can explore.


That's all I got! I hope it helps save your time in case you ever need to try it out.

Khairah Signature.gif