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>[email protected]</td>
<td>India,up</td>
</tr>
<tr>
<td>Stephen Thomas</td>
<td>[email protected]</td>
<td>UK,london</td>
</tr>
<tr>
<td>Natly Oath</td>
<td>[email protected]</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.
-
1Do 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 L– Andrew L2018年11月20日 18:51:32 +00:00Commented Nov 20, 2018 at 18:51
-
This would be a good read for you too- stackoverflow.com/questions/769621/…Andrew L– Andrew L2018年11月20日 18:54:47 +00:00Commented Nov 20, 2018 at 18:54
-
@AndrewLohr hey, i meant it for India and up similarly UK and londonSri Ranjan– Sri Ranjan2018年11月20日 19:03:50 +00:00Commented Nov 20, 2018 at 19:03
1 Answer 1
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);
}
answered Nov 20, 2018 at 19:35
suresh bambhaniya
1,6871 gold badge14 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
suresh bambhaniya
If solution is works then please mark as correct then future user easily find out correct answer
lang-js