0

Following my previous query:

HTML form output as a table

I would like to export my HTML form output to Excel.

I found several examples on the web and tried some of them...

https://www.revisitclass.com/css/how-to-export-download-the-html-table-to-excel-using-javascript/

https://www.codexworld.com/export-html-table-data-to-csv-using-javascript/

https://odoepner.wordpress.com/2012/04/09/export-to-html-table-as-csv-file-using-jquery/

In all cases, I get only the column titles instead of other rows, as you can see below:

enter image description here

There is something wrong with the Element.append() which can't be picked up properly

My code looks as follows:

    <table id="opresults" class="outputtable"><p class="outputtablehead">Survey Form - output</p>
     <tr class="colname">
       <th class="question">Form question</th>
       <th colspan="2" class="answer">Answer</th>
     </tr>
     <tr>
        <td></td>
        <td></td>
     </tr>
    </table>

        <script>
        const resultsList = document.getElementById('opresults')
        const matches = document.querySelectorAll("fieldset");

        new URLSearchParams(window.location.search).forEach((value, name) => {
            resultsList.append(document.createElement('tbody'))
            resultsList.append(`${name}`)
            resultsList.append(document.createElement('td'))
            resultsList.append(`${value}`)
            resultsList.append(document.createElement('br'))   
            })
           </script>

and another script, which exports the file to .csv is included here:

https://jsfiddle.net/c0urwa5g/1/

Is there any way to include the append() method in this .csv export?

As per another example:

How to export JavaScript array info to csv (on client side)?

It looks like I have to define the column and row names. Unfortunately, I can't here, because they are input-dependant. Is there a way to solve this issue?

The code with another approach is here:

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);
  }
Geographos
  • 827
  • 2
  • 23
  • 57

1 Answers1

0

You aren't creating row elements or inserting cells in those row elements or inserting text into the cells you are creating

You are trying to append everything directly into the table element and that won't work.

You can simplify this using Table.insertRow() and Row.insertCell()

initDemo()

const resultsList = document.getElementById('opresults');

new URLSearchParams(window.location.search).forEach((value, name) => {
  const row = resultsList.insertRow();
  [name, value].forEach(v => row.insertCell().textContent = v); 
})


// for demo only - creates initial url search params
function initDemo() {
  const params = new URLSearchParams([
    ["issue_1", "answer_1"],
    ["thing_2", "answer_2"]
  ]);
  history.pushState(null, null, '?' + params.toString())


}
<p class="outputtablehead">Survey Form - output</p>
<table id="opresults" class="outputtable" border="1">
  <tr class="colname">
    <th class="question">Form question</th>
    <th colspan="2" class="answer">Answer</th>
  </tr>
</table>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • It would be beneficial, although I need the stuff from my form. The "issue_1 and "answer_1" should be replaced by something like: [${name}, ${value}] – Geographos May 12 '21 at 12:43
  • Those are just dummy values in order to populate a search string in url. I assumed you were already submitting the form to generate that url. If not - the question is misleading – charlietfl May 12 '21 at 12:45
  • I want the column rows to be picked up by the Export to CSV function regarding their names and content. Is it possible? – Geographos May 12 '21 at 12:52
  • Certainly, that's why you first need the valid table – charlietfl May 12 '21 at 12:53
  • Perhaps you don't even need the table? Converting form directly to csv is also a fairly easy operation – charlietfl May 12 '21 at 12:56
  • I created a table, because I could only find export HTML to CSV based on table. How can I convert it directly to CSV then? – Geographos May 12 '21 at 15:05
  • Hmm, it looks like I posted this question badly :( Maybe will be better when I upload the form to the web and will back to you. What you are proposing is downloading .csv from the file, where the form is based. I have my form in another file, and net I use the element.Append() property in order to build up the table from the data passed from the form. – Geographos May 12 '21 at 16:06