7

Is there any way to get an HTML page to read a csv file from a particular destination and display it as an HTML table in the web page?

I am developing a web page to display the status of users that are logged in. Therefore the HTML page has to automatically read the csv file and display it in a web page accordingly, since the csv file will be updated periodically.


Edit:

Added the code as per suggestion from the answer, but nothing pops up in the browser

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>CSV Downloader</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
    function arrayToTable(tableData) {
        var table = $('<table></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            $(rowData).each(function (j, cellData) {
                row.append($('<td>'+cellData+'</td>'));
            });
            table.append(row);
        });
        return table;
    }

    $.ajax({
        type: "GET",
        url: "C:\Users\tim tom\Desktop\csvTOhtml\data.csv",
        success: function (data) {
            $('body').append(arrayToTable(Papa.parse(data).data));
        }
    });
</script>
</body> 
John Slegers
  • 45,213
  • 22
  • 199
  • 169
ddpd
  • 603
  • 1
  • 10
  • 25

1 Answers1

16

Three step process

You need three steps :

1) Use Ajax to fetch data from your server and turn it into an array. You could do this eg. with the following jQuery :

$.ajax({
    type: "GET",
    url: "data.csv",
    success: CSVToHTMLTable
});

2) Once you have get your CSV file, you need to parse it. An easy & reliable way to do it, would be to use a library like Papa Parse :

var data = Papa.parse(data).data;

3) You need to define a function to transform your array into an HTML table. Here's how you could do this with jQuery :

function arrayToTable(tableData) {
    var table = $('<table></table>');
    $(tableData).each(function (i, rowData) {
        var row = $('<tr></tr>');
        $(rowData).each(function (j, cellData) {
            row.append($('<td>'+cellData+'</td>'));
        });
        table.append(row);
    });
    return table;
}

Putting everything together

Here's how you can put everything together :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
    function arrayToTable(tableData) {
        var table = $('<table></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            $(rowData).each(function (j, cellData) {
                row.append($('<td>'+cellData+'</td>'));
            });
            table.append(row);
        });
        return table;
    }

    $.ajax({
        type: "GET",
        url: "http://localhost/test/data.csv",
        success: function (data) {
            $('body').append(arrayToTable(Papa.parse(data).data));
        }
    });
</script>
John Slegers
  • 45,213
  • 22
  • 199
  • 169
  • 1
    Need to transform csv text to javscript array before you can use `forEach`. Also `dataType` is invalid...see docs – charlietfl Mar 19 '16 at 16:34
  • @charlietfl : You're right. I forgot that jQuery doesn't auto-parse CSV. I just updated my answer with a more complete procedure! – John Slegers Mar 19 '16 at 17:07
  • @JohnSlegers . Where should my data.csv file stored? Also please have a look at my code in my question post. Thanks – ddpd Mar 20 '16 at 03:38
  • @ddpd : Your data.csv should be stored in a public location on the same server as the script you're running. So if your domain is `www.mydomain.com`, you could put it eg. at `www.mydomain.com/data.csv` – John Slegers Mar 20 '16 at 14:51
  • 1
    @ddpd : `C:\Users\tim tom\Desktop\csvTOhtml\data.csv` won't work, because it's a local path. If you want it to run locally on your laptop / desktop computer, you'll need to install a web server like Apache and then put your script in the folder that corresponds with `http://localhost`. – John Slegers Mar 20 '16 at 14:55
  • @JohnSlegers: Oh I see.. Then I will test in windows server and let you know. May I know the reason for not displaying in local PC? Also, do I need to modify the script except the file path as posted in the question? – ddpd Mar 20 '16 at 16:16
  • @ddpd : `May I know the reason for not displaying in local PC?` -> Ajax involves making HTTP requests... which means that your path needs to be available via HTTP -- Anyway, I tested the script I posted in my answer locally. It worked perfectly for me on my laptop, where I'm running an Apache server. – John Slegers Mar 20 '16 at 16:50
  • @JohnSlegers: Yeah it worked. I was modifying windows server IIS manager web page.I have one doubt. How do I reload the table automatically if there is any change in csv file. Also this table is not displayed inside the main page, instead it is displayed outside. Is it possible to do display within the main page? – ddpd Mar 21 '16 at 16:02
  • @ddpd: (1) What you do mean by "main" page? Anyway, where I put `$('body')`, the values between the `$()` should be whatever HTML element you want to add your table to. (2) To keep your table up to date, you could to a `setInterval` or `setTimeout` to remove your table and replace it with the new values every time a change is detected. – John Slegers Mar 21 '16 at 16:07
  • @JohnSlegers: The thing is when I simply define a table in html, using table, td, tr it is displayed within a page which belongs to a section where other text are displayed. But when this part of your code is called, the table are displayed as a separate entity which does not belong to that main text.. Can I get an example for set Interval with the code you posted. Your explanation seems to be very descriptive. Hence can understand easily. Thanks – ddpd Mar 21 '16 at 16:19
  • @ddpd : Please post a demo of what you're trying to do on https://jsfiddle.net/. That would make it a lot easier for me to determine what you could do. – John Slegers Mar 21 '16 at 17:57
  • How to apply css style using this approach (like column header bold, row colour etc). Please provide some guidance – Ashu Aug 10 '22 at 00:04
  • @Ashu : At the lines `var table = $('
    ');`, `var row = $('');`, and `row.append($(''+cellData+''));`, just add an `id` or `class`. Then, add some CSS for that `id` or `class` to the rest of your CSS code.
    – John Slegers Aug 11 '22 at 21:29