How to Export a React Table data on the frontend in CSV format.

How to Export a React Table data on the frontend in CSV format.

I have a table component that renders data in react, And a button above the table component to spool the record into an excel sheet in CSV format, To achieve this functionality on the frontend without making any API calls.

Since Reactjs is basically JavaScript, you need to write a function named "handleTableExport"

handleTableExport = () => {
let result= [];
let rows = document.querySelectorAll("table tr");
for (let i = 0; i < rows.length; i++) {
   let row = []; //temporary array to save each row content;
let cols = rows[i].querySelectorAll("td, th");
   for (let j = 0; j < cols.length; j++) {
      row.push(cols[j].innerText);
   }
  result.push(row);
}
this.downloadCSVFile(result.join("\n"), "Report.csv");
};

That select all the rows in the table component then iterate over them, get all columns in that row, and loop through the columns in order to save each "td" and "th" values in our temporary array "row ([])", as soon as we are done pushing each column value into the row array, we then have to push our temporary array separated by comma, into our final result array. At then end of our loops, we have another function that receives two parameters (the result array and the name we want to save the file as), and perform just one thing which is using Blob, to generate the file in csv format and downloading the csv file on the fly.

downloadCSVFile = (csv, filename) => {
let csv_file, link;
csv_file = new Blob([csv], { type: "text/csv" });
link = document.createElement("a");
link.download = filename;
link.href = window.URL.createObjectURL(csv_file);
link.style.display = "none";
document.body.appendChild(download_link);
link.click();
};

N.B: A Blob is simply a group of bytes that holds the data stored in a file. It has size and MIME type just like a file, and its data is stored in the memory or filesystem depending on the browser and blob size.

Conclusion

So with these two functions we can now handle the functionality of spooling table data in react into csv format on the frontend.