0

I am making a simple table page and I don't want to manually add rows using HTML. I have about 100 rows of data and I am working in a Static Environment so JavaScript is the only option I have (or the only one I know maybe able to do this).

I did try some tutorials and did find a way to import CSV to HTML. I used this tutorial and it worked like charm.

But the issue is that the tutorial uses an <input> tag to get the File Object. I only have a single CSV file locally stored in the same folder as the Web Page. I tried looking up for File objects and Blobs but I am not able to make it work so far. None of my functions work.

Here's what I want my page to do:

Upon opening, I want my page to directly load the data from the CSV and put it in A Table. I do know how to add table code to the html page using innerHTML but I just haven't been able to import the actual CSV data. Please help!

1 Answer 1

2

For security reasons it is not allowed to read OS files with JS from the browser. For this you must have the CSV file and the html page from where you want to read it on the same server and using ajax or some server side language generate a JSON. I give you an example in ajax

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "datatable.txt",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(allText) {
    var record_num = 5;  // or however many columns there are in each row
    var allTextLines = allText.split(/\r\n|\n/);
    var entries = allTextLines[0].split(',');
    var lines = [];

    var headings = entries.splice(0,record_num);
    while (entries.length>0) {
        var tarr = [];
        for (var j=0; j<record_num; j++) {
            tarr.push(headings[j]+":"+entries.shift());
        }
        lines.push(tarr);
    }
    // alert

OR use this library https://www.cssscript.com/lightweight-csv-table-converter-csvtotable-js/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was able to do it using your solution! Although it worked, I used an alternative too. I used a Python script I made to parse the CSV and basically convert it to HTML. It is just a work around since I am using Github to host my page and I am pretty sure we can't use Server Side Languages on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.