The following DEMO allows you to export the HTML Table as CSV by clicking "Export to CSV" button.
However, if you look at the exported CSV you'll notice that in the last row:
"00001" get truncated to just "1"
function download_csv(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;
// We have to create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);
// Make sure that the link is not displayed
downloadLink.style.display = "none";
// Add the link to your DOM
document.body.appendChild(downloadLink);
// Lanzamos
downloadLink.click();
}
function export_table_to_csv(html, 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
download_csv(csv.join("\n"), filename);
}
document.querySelector("#button2").addEventListener("click", function () {
var html = document.querySelector("table").outerHTML;
export_table_to_csv(html, "table.csv");
});
<table border="1px">
<thead>
<tr>
<th>ID</th>
<th>PROVINCE</th>
<th>DIVISION</th>
<th>NAME</th>
</tr>
</thead>
<tbody>
<tr><td>76363</td><td>Province1</td><td>AA</td><td>NAME1</td></tr>
<tr><td>76371</td><td>Province2</td><td>AB</td><td>NAME2</td></tr>
<tr><td>76388</td><td>Province3</td><td>AC</td><td>NAME3</td></tr>
<tr><td>76424</td><td>Province4</td><td>AD</td><td>NAME4</td></tr>
<tr><td>00001</td><td>undefined</td><td>undefined</td><td>undefined</td>
</tr>
</tbody>
</table>
<button id="button2">Export to CSV</button>
I want to preserve the leading zeroes with any data I might put in the table.
The only way to do that is by adding an apostrophe ' BEFORE the number that starts with 0.
In other words: 00001 will turn to '00001
I am assuming the solution is to add an:
IF <td> starts with 0 add ' statement.
How to do that?
innerTextjust returns a string; it does not know that the contained value is aNumber.