I have a HTML file. It has Pre-formatted text with CSV data in it.
<pre>1,2,3,4
5,6,7,8
9,0,1,2
3,4,5,6
</pre>
How to extract this data and convert it into a HTML table using Javascript?
I have a HTML file. It has Pre-formatted text with CSV data in it.
<pre>1,2,3,4
5,6,7,8
9,0,1,2
3,4,5,6
</pre>
How to extract this data and convert it into a HTML table using Javascript?
Use the function described in this answer. It returns an array if you give it CSV data. So given the data:
<pre id="CSV_DATA">1,2,3,4
5,6,7,8
9,0,1,2
3,4,5,6
</pre>
You can get the CSV into a Javascript string:
var csv_data = document.getElementById("CSV_DATA").innerHTML;
Then use the function CSVToArray
to get an array of the data:
var array_data = CSVToArray(csv_data, ",");
Then make an HTML table:
var table=document.createElement('table');
table.border='1';
document.body.appendChild(table);
for(var i=0; i<array_data.length; i++){
var line = array_data[i];
var tr=document.createElement('tr');
for(var j=0; j<line.length; j++){
var td=document.createElement('td');
td.innerHTML = line[j];
tr.appendChild(td);
table.appendChild(tr);
}
}
I haven't tested this code. Please review it and work out the details. But what it's supposed to do is iterate through the array returned by CSVToArray
and add each element of that array to a table row, then add each generated row to a table. The table is added to the document's body, but you can add it wherever you please.
And here's a demo of mine as well.
If you know that the data is going to be in the exact format you gave, then something simple like this will work:
Markup:
<pre id="data">1,2,3,4
5,6,7,8
9,0,1,2
3,4,5,6</pre>
<div id="table"></div>
JavaScript:
var table = '';
var rows = new Array();
rows = document.getElementById('data').innerHTML.split('\n');
table += '<table>'
for(var i = 0; i < rows.length; i++) {
var columns = rows[i].split(',');
table += '<tr>';
for(var j = 0; j < columns.length; j++) {
table += '<td>' + columns[j] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('table').innerHTML = table;