0

i found this code to download my table content into csv format but the problem is my table field has comma(,) within its field but the function splits the field.

these are the functions:

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

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


                downloadLink = document.createElement("a");

                downloadLink.download = filename;

                downloadLink.href = window.URL.createObjectURL(csvFile);


                downloadLink.style.display = "none";

                document.body.appendChild(downloadLink);


                downloadLink.click();
            }


        function exportTableToCSV(filename) {
            var csv = [];
            var rows = document.querySelectorAll("table 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);
        }

here is the html code:

<table>
    <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Location</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>john@gmail.com</td>
        <td>India,up</td>
    </tr>
    <tr>
        <td>Stephen Thomas</td>
        <td>stephen@gmail.com</td>
        <td>UK,london</td>
    </tr>
    <tr>
        <td>Natly Oath</td>
        <td>natly@gmail.com</td>
        <td>France</td>
    </tr>
</table>

<button onclick="exportTableToCSV('members.csv')">Export HTML Table To CSV 
File</button>

the location column of john and natly will be split.

  • 1
    Do you mean it will split for John and Stephen? Also have you tried to alter the code yourself? It would help us if you showed an attempt as we can guide you through that. – Andrew Lohr Nov 20 '18 at 18:51
  • This would be a good read for you too- https://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file – Andrew Lohr Nov 20 '18 at 18:54
  • @AndrewLohr hey, i meant it for India and up similarly UK and london – Sri Ranjan Nov 20 '18 at 19:03

1 Answers1

5

you can use quotes to ignore comma

 function exportTableToCSV(filename) {
            var csv = [];
            var rows = document.querySelectorAll("table 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);
        }
suresh bambhaniya
  • 1,687
  • 1
  • 10
  • 20