Convert HTML tables to CSV files
htmlTableToCsv()
<table id="my-table">
<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>
<button onclick="htmlTableToCsv('my-table', 'table-data')">Download as CSV</button>
When the user clicks the button, the htmlTableToCsv
function will be called, converting the data in the HTML table with the ID my-table
to a CSV file and downloading it to the user’s computer with the name table-data.csv
.
getCsvString()
HTML:
<table id="myTable">
<tr>
<td>Column 1, Row 1</td>
<td>Column 2, Row 1</td>
</tr>
<tr>
<td>Column 1, Row 2</td>
<td>Column 2, Row 2</td>
</tr>
</table>
JavaScript:
const csvString = getCsvString('myTable');
console.log(csvString);
The output of the code above would be:
Column 1, Row 1,Column 2, Row 1
Column 1, Row 2,Column 2, Row 2