Search code examples
javascriptarraysexport-to-excel

Saving HTML Table data in order in Excel File


I am converting HTML table data to Excel CSV file and I am using the below code:

<script>

    function downloadCSV(csv, filename) {
        var csvFile;
        var downloadLink;

        // CSV file
        csvFile = new Blob([csv], {type: "text/csv"});

        // Download link
        downloadLink = document.createElement("a");

        // File name
        downloadLink.download = filename;

        // Create a link to the file
        downloadLink.href = window.URL.createObjectURL(csvFile);

        // Hide download link
        downloadLink.style.display = "none";

        // Add the link to DOM
        document.body.appendChild(downloadLink);

        // Click download link
        downloadLink.click();
    }



    function exportTableToCSV(filename) {
        var csv = [];
        var rows = document.querySelectorAll("#faqs tr");
        for (var i = 0; i < rows.length; i++) {

            var row = [], cols = rows[i].querySelectorAll("td, th");

            for (var j = 0; j < cols.length; j++)
                row.push(cols[j].innerText);

            csv.push(row.join(","))
        }

        // Download CSV file
        downloadCSV(csv.join("\n"), filename);
    }

</script>

The problem is when this script generates Excel sheet it is not in proper format.

From the image you can see that the Question Column has text which contains commas , so that commas are making the problem. And all the Excel fields are not in the format which I want. I want to list all the data related to columns in their respective columns but the Question columns is confusing the script.

Button:

  <button onclick="exportTableToCSV('faqs.csv')"> Export CSV</button>

Data in excel


Solution

  •   for (columnCounter = 0; columnCounter < totalColumns; columnCounter++) {
        // quote each column in order to escape any commas
        row.push('"' + cols[columnCounter].innerText + '"');
      }
    

    https://jsbin.com/zepabey/edit?html,console,output