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

Chisom Okoye

--

screenshot of where I made use of the function.

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);
}
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.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Chisom Okoye
Chisom Okoye

Written by Chisom Okoye

front end developer, Javascriptor

No responses yet

Write a response