Skip to content Skip to sidebar Skip to footer

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 be

Solution 1:

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:

functioncreateTable() {
    vararray = [[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

<inputtype="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 = newFileReader();
    var f = file.files[0];
    reader.onload = function(e) {
        varCSVARRAY = 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.

functionparseResult(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)

Solution 2:

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.

Post a Comment for "Loading A Csv File Into An Html Table Using Javascript"