0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bharath119
  • 23
  • 1
  • 5

2 Answers2

2

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.

Community
  • 1
  • 1
2

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;

Demo

Zhihao
  • 14,758
  • 2
  • 26
  • 36
  • Thanks for your reply. It worked for me. But, I need a simple alteration for it. I want borders around each cell. I will be very grateful if you help me with this one. Thank you. – bharath119 Jun 17 '12 at 06:03
  • @bharath119 You can use some CSS. Here is Jia's solution with some CSS added: http://jsfiddle.net/UPsjZ/. –  Jun 17 '12 at 09:46