Reactjs Table to CSV file convert
To convert a table to a CSV file in React, you can use the TableToCsv
component below. This component uses the toString()
method of the Blob
object to convert a table to a CSV file and prompt the user to download it.
Here is an example of how you can use the TableToCsv
component:
import React from 'react';
import TableToCsv from './TableToCsv';
function App() {
return (
<div>
<table id="myTable">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
</tr>
</table>
<TableToCsv tableId="myTable" fileName="myTable.csv" />
</div>
);
}
export default App;
The TableToCsv
component takes two props: tableId
and fileName
. tableId
is the ID of the table that you want to convert to a CSV file, and fileName
is the name of the CSV file that will be downloaded.
Here is the code for the TableToCsv
component:
import React from 'react';
function TableToCsv(props) {
const tableId = props.tableId;
const fileName = props.fileName;
function downloadCsv() {
const table = document.getElementById(tableId);
let csv = '';
for (let i = 0; i < table.rows.length; i++) {
const rowData = table.rows[i].cells;
for (let j = 0; j < rowData.length; j++) {
csv += rowData[j].innerHTML + ',';
}
csv += '\n';
}
const hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = fileName;
hiddenElement.click();
}
return <button onClick={downloadCsv}>Download CSV</button>;
}
export default TableToCsv;
I hope this helps! Let me know if you have any questions.
Post a Comment