Faiz Hameed
Faiz Hameed

Reputation: 544

How to merge or combine cells when converting html table to csv using javascript

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

new csv output

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>

Upvotes: 0

Views: 1308

Answers (1)

John
John

Reputation: 6278

CSV does not support column widths. They are Comma Separated Values which means each column is separated by a comma.

You can put the "Details List" in the "Center" by putting a comma before it in that row so that it goes to the second column, but it will not automatically center itself.

The file format you would need for that would be xlsx which is much more complicated.

Edit: also if you want to manipulate CSVs in the future. You can use papa parse.

Upvotes: 2

Related Questions