DeveloperBreeze

Export To Csv Development Tutorials, Guides & Insights

Unlock 1+ expert-curated export to csv tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your export to csv skills on DeveloperBreeze.

Exporting Table Row Data to CSV in JavaScript

Tutorial October 24, 2024
php

// Select all export buttons
const exportButtons = document.querySelectorAll('.export-btn');

// Add event listener to each export button
exportButtons.forEach(button => {
    button.addEventListener('click', () => {
        // Get the parent row of the clicked button
        const row = button.closest('tr');

        // Get all cells in the row except the last one (which contains the export button)
        const cells = Array.from(row.querySelectorAll('td'));
        cells.pop(); // Remove the last cell (the button cell)

        // Extract the text content of each cell and wrap them in double quotes (CSV format)
        const cellValues = cells.map(cell => `"${cell.textContent}"`);

        // Create the CSV data by joining cell values with commas
        const csvData = cellValues.join(',');

        // Create a temporary anchor element for the download
        const anchor = document.createElement('a');
        anchor.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csvData);
        anchor.download = 'row_data.csv';

        // Programmatically click the anchor to trigger the download
        anchor.click();
    });
});
  • querySelectorAll('.export-btn'): Selects all elements with the class export-btn, i.e., the export buttons.
  • closest('tr'): This retrieves the closest table row (<tr>) that contains the clicked button.
  • querySelectorAll('td'): Retrieves all the <td> cells in the row.
  • Array.from(): Converts the list of cells into an array, which allows us to manipulate it easily.
  • cells.pop(): Removes the last cell (the one containing the export button), as we don’t want it in the CSV.
  • textContent: Extracts the text content from each cell.
  • encodeURIComponent(): Encodes the CSV string, making it safe for use in a URL.
  • anchor.download: Specifies the filename for the CSV file (in this case, row_data.csv).
  • anchor.click(): Programmatically triggers a click on the anchor element, which starts the download.