Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a CSV file into an HTML table using javascript

I want to create a webpage that loads a selected CSV file (from hard drive) and displays its contents using table HTML.

The project incorporates two components and so far, I've been researching the latter; generating a table out of a nested array in javascript.

For some reason, the columns do not appear the way they should.

My code

<!DOCTYPE html>
<html>
<body>

<table id="1"> </table>

<button onclick="createTable()">Create</button>

<script>
function createTable() {
    var array = [[1,2,3],[4,5,6],[7,8,9]];
	document.getElementById("1").innerHTML = ""; //Clear.
	
	for (i = 0; i < array.length; i++) { 
	document.getElementById("1").innerHTML += "<tr>";
		for (k = 0; k < array[0].length; k++) {
		  document.getElementById("1").innerHTML += "<td>" + array[i][k] + "</td>" ;
		}
		document.getElementById("1").innerHTML += "</tr>";
	  }
}
</script>

</body>
</html>
like image 236
John Avatar asked Feb 08 '23 04:02

John


2 Answers

Save the table contents to a variable first and set it to the innerHTML afterwards. Everytime you add a <tr> (or any not singleton tag for that matter), the browser immediately renders the closing tag.

Try this:

function createTable() {
    var array = [[1,2,3],[4,5,6],[7,8,9]];
    var content = "";
    array.forEach(function(row) {
        content += "<tr>";
        row.forEach(function(cell) {
            content += "<td>" + cell + "</td>" ;
        });
        content += "</tr>";
    });
    document.getElementById("1").innerHTML = content;
}

Because you are planning on using the FileReader API, IE9 support is off the table anyways. Updated the above function to use the 'newer' forEach array function


ADDENDUM

To load a file with javascript you have to use the FileReader HTML5 API. I can give you some pointers as to how you should go about doing this. This is all untested code, but it gives you a little idea what to do

1.Create a input field

<input type="file" id="file" name="file">

2.Trigger a response on change of this input

var file = document.getElementById('file');
file.addEventListener('change', function() {
    var reader = new FileReader();
    var f = file.files[0];
    reader.onload = function(e) {
        var CSVARRAY = parseResult(e.target.result); //this is where the csv array will be
    };
    reader.readAsText(f);
});

3.Parse the result to an array by using split/push. This uses \n as row delimiter and , as cell delimiter.

function parseResult(result) {
    var resultArray = [];
    result.split("\n").forEach(function(row) {
        var rowArray = [];
        row.split(",").forEach(function(cell) {
            rowArray.push(cell);
        });
        resultArray.push(rowArray);
    });
    return resultArray;
}

(or you can use a third party plugin which will parse the CSV for you: papa parse, for instance)

like image 77
Poul Kruijt Avatar answered Feb 16 '23 04:02

Poul Kruijt


After some long searching, this is probably the most simple and functional script that I could ever come across, also available for free. Although it doesn't deal with the array modification directly, it's easy to edit and elicit your desired results.

like image 25
John Avatar answered Feb 16 '23 04:02

John