Export HTML Tables as CSV with JavaScript – Table2CSV

Category: Javascript , Table | September 25, 2024
Authormxsena
Last UpdateSeptember 25, 2024
LicenseMIT
Tags
Views98 views
Export HTML Tables as CSV with JavaScript – Table2CSV

Table2CSV is a tiny JavaScript library that transforms HTML tables into downloadable CSV files. It works directly in the browser without external dependencies.

This table-to-CSV converter can be useful for data analysis, reporting, and integration with spreadsheet software. Instead of just viewing the data on the page, users can download it as a CSV file for further analysis in spreadsheet software like Excel or Google Sheets.

How to use it:

1. Add a unique ID to your HTML table:

<table id="myTable" class="table">
  ...
</table>

2. Include this JavaScript function in your code.

The downloadCSV function first retrieves the table element using its ID. It then iterates through each row and cell of the table. The content of each cell is extracted, and any commas within the cell content are removed to prevent issues with the CSV format. The extracted cell data is then joined together with commas to form a single row in the CSV string. Each row is appended to the csvContent variable, separated by a newline character.

Once the entire table data is converted to a CSV string, a Blob object is created from it, specifying the MIME type as ‘text/csv’. A temporary URL is created for this Blob using URL.createObjectURL. A hidden anchor element (<a>) is created, and its href attribute is set to the temporary URL. The download attribute is set to the desired filename for the CSV file. This anchor element is then appended to the document body, programmatically clicked to trigger the download, and finally removed from the body.

function downloadCSV() {
    const table = document.getElementById('myTable');
    let csvContent = '';
    for (let i = 0; i < table.rows.length; i++) {
        let row = table.rows[i];
        let rowData = [];
        for (let j = 0; j < row.cells.length; j++) {
            let cell = row.cells[j];
            rowData.push(cell.textContent.replace(/,/g, ''));
        }
        csvContent += rowData.join(',') + '\r\n';
    }
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'table-data.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

3. Call the downloadCSV function to download the CSV:

downloadCSV()

You Might Be Interested In:


Leave a Reply