Using javascript I'm able to create a table. But I wanted to add a header to this table by merging all cells in the top row
This is my existing code to convert HTML table to CSV. But here I am unable to create a header with 'some title' that spans to the entire column.
So the output should look something like this
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("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);
}
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Country</th>
</tr>
<tr>
<td>John Doe</td>
<td>[email protected]</td>
<td>USA</td>
</tr>
<tr>
<td>Stephen Thomas</td>
<td>[email protected]</td>
<td>UK</td>
</tr>
<tr>
<td>Natly Oath</td>
<td>[email protected]</td>
<td>France</td>
</tr>
</table>
<button onclick="exportTableToCSV('ps_file.csv')">
Export HTML Table To CSV File
</button>
