Reactjs: Download CSV File on Button Click

How to save CSV file from API response using React?

As suggested by @cocco in this thread, you could dynamically generate an anchor with the download attribute.

NOTE: For the sake of simplicity, I'll demo getting the data part form an API using a useEffect and a fake HttpClient service that has a static get method that returns the data. But hope you get the general idea.

import React, { useState, useEffect } from "react";

import HttpClient from "./HttpClient";
import "./style.css";

export default function App() {
const [dataInCSV, setDataInCSV] = useState("");

useEffect(() => {
HttpClient.get().then(res => setDataInCSV(res));
}, []);

return (
<div>
{dataInCSV && (
<a
href={`data:text/csv;charset=utf-8,${escape(dataInCSV)}`}
download="filename.csv"
>
download
</a>
)}
</div>
);
}

Here's a Working Sample Code Example for your ref.

how to export the return table data to a csv file using react js

A library like react-csv will help you to export data to a csv file easily, here is an example :

import { CSVLink, CSVDownload } from "react-csv";

let names = [
{firstName: 'John',lastName: 'Cena'},
{firstName: 'Rey',lastName: 'Mysterio'},
]

const App = props => {
return (
<>
<CSVLink data={names}>Download me</CSVLink>;
// or
<CSVDownload data={names} target="_blank" />;
</>
);
};

For more information about the library visit: https://www.npmjs.com/package/react-csv

Export to CSV button in react table

Here is what the integration will look like:

import React from "react";
import "react-dropdown/style.css";
import "react-table/react-table.css";
import ReactTable from "react-table";
import { CSVLink } from "react-csv";

const columns = [
{
Header: "name",
accessor: "name", // String-based value accessors!
},
{
Header: "age",
accessor: "age",
},
];

class AllPostPage extends React.Component {
constructor(props) {
super(props);
this.download = this.download.bind(this);
this.state = {
tableproperties: {
allData: [
{ name: "ramesh", age: "12" },
{ name: "bill", age: "13" },
{ name: "arun", age: "9" },
{ name: "kathy", age: "21" },
],
},
dataToDownload: [],
};
}

download(event) {
const currentRecords = this.reactTable.getResolvedState().sortedData;
var data_to_download = [];
for (var index = 0; index < currentRecords.length; index++) {
let record_to_download = {};
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
record_to_download[columns[colIndex].Header] =
currentRecords[index][columns[colIndex].accessor];
}
data_to_download.push(record_to_download);
}
this.setState({ dataToDownload: data_to_download }, () => {
// click the CSVLink component to trigger the CSV download
this.csvLink.link.click();
});
}

render() {
return (
<div>
<div>
<button onClick={this.download}>Download</button>
</div>
<div>
<CSVLink
data={this.state.dataToDownload}
filename="data.csv"
className="hidden"
ref={(r) => (this.csvLink = r)}
target="_blank"
/>
</div>
<div>
<ReactTable
ref={(r) => (this.reactTable = r)}
data={this.state.tableproperties.allData}
columns={columns}
filterable
defaultFilterMethod={(filter, row) =>
String(row[filter.id])
.toLowerCase()
.includes(filter.value.toLowerCase())
}
/>
</div>
</div>
);
}
}

export default AllPostPage;

This will work with filters as well.

How to let the user download data (CSV) in React?

You can use FileSaver, which is a great tool to manage files on client-side.

Your code should look like this:

import FileSaver from 'file-saver';

function handleExport() {
const csv = convertContactsToCSV(contacts);
const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' });

FileSaver.saveAs(csvData, 'data.csv');
}


Related Topics



Leave a reply



Submit