0

I have a standalone HTML page (no webserver) and I'm after some javascript code that will display the contents of a .csv file in the page.

The .csv file contains a list of usernames that I would like to be displayed. I'm doing it this way as the people that need to update the list know nothing of HTML and initially thought this would be an easier way to do it.

All the code snippets that I have found either try to upload a file and then only display the contents till you reload the page again or I don't have enough knowledge to tweak the code to work.

Any help appreciated & TYIA

Andy

@Barthy code that is very close to what I would like is this:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            table {
            border-collapse: collapse;
            border: 2px black solid;
            font: 12px sans-serif;
            }
            td {
            border: 1px black solid;
            padding: 5px;
            }
        </style>
    </head>
    <body>
        <div id='container'></div>
        <script type="text/javascript"charset="utf-8">
        var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
        var lines = data.split("\n"),
        output = [],
        i;
        for (i = 0; i < lines.length; i++)
        output.push("<tr><td>"
        + lines[i].slice(0,-1).split(",").join("</td><td>")
        + "</td></tr>");
        output = "<table>" + output.join("") + "</table>";
        var div = document.getElementById('container');

        div.innerHTML = output;
        </script>
   </body>
</html>

but would like to get data from CSV file

@cars10 example of what is in the csv file:

Heading_1,Heading_2,Heading_3,Heading_4
John,     Smith,    29,       Male
Andy,     Jones,    32,       Male
Abbey,    Stewart,  35,       Female

if that helps

Solution so far:

<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
        <style>
            table {
            border-collapse: collapse;
            border: 2px black solid;
            font: 12px sans-serif;
            }
            td {
            border: 1px black solid;
            padding: 5px;
            }
        </style>

        <script>
            window.onload=function(){ with (new XMLHttpRequest()) {
            onreadystatechange=cb; open('GET','data.csv',true); responseType='text';send();
            }}
            function cb(){if(this.readyState===4)document.getElementById('main')
                                         .innerHTML=tbl(this.responseText); }
            function tbl(csv){ // do whatever is necessary to create your   table here ...
            return csv.split('\n')
            .map(function(tr,i){return '<tr><td>'
                                 +tr.replace(/\t/g,'</td><td>')
                                 +'</td></tr>';})
        .join('\n'); }
        </script>
        </head>
        <body>
            <h2>Hey, this is my fabulous "dynamic" html page!</h2>
            <table id="main"></table>
        </body>
    </html>
Andy M
  • 167
  • 1
  • 3
  • 17
  • Do you have example code? How exactly does the csv file look like? What have you tried exactly? We can help solve specific problems, right now you are kind of asking to do all your work for you. – Barthy Aug 01 '17 at 15:25
  • Does the content of CSV file change? – Nisarg Shah Aug 01 '17 at 15:26
  • @Barthy added the nearest code I have though I need to populate 'data' with what is in the .csv file called data.csv – Andy M Aug 01 '17 at 17:02
  • @NisargShah the csv file only changes when a new user is added to it – Andy M Aug 01 '17 at 17:03
  • @madmiddle so the only problem you have is to get the contents from the csv file instead of a string? – Barthy Aug 01 '17 at 17:07
  • @Barthy I apologise in advance for my bad choice of words as my limited knowledge is preventing me from explaining this properly. My end goal is to display the contents of the .csv file on a HTML page in a table format. That example code turns a string (that I would assume you would get from a .csv file) into a nice looking table. the link I'm struggling with is getting the data from the .csv file in the first place. – Andy M Aug 01 '17 at 17:17
  • then I think @cars10 's answer should provide help :) – Barthy Aug 01 '17 at 17:24

1 Answers1

5

Here is a complete working example (works even on a local directory, i.e. no web server at all!). This is a plain JavaScript solution. Personally, I would always use jquery, but in this simple case you can do without it.

The page expects the csv-file ("csv.txt") in the same directory. But it is up to you to specify another (relative) path in the oReq.open() line.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload=function(){ with (new XMLHttpRequest()) {
  onreadystatechange=cb; open('GET','csv.txt',true); responseType='text';send();
}}
function cb(){if(this.readyState===4)document.getElementById('main')
                                             .innerHTML=tbl(this.responseText); }
function tbl(csv){ // do whatever is necessary to create your table here ...
 return csv.split('\n')
           .map(function(tr,i){return '<tr><td>'
                                     +tr.replace(/\t/g,'</td><td>')
                                     +'</td></tr>';})
           .join('\n'); }
</script>
</head>
<body>
<h2>Hey, this is my fabulous "dynamic" html page!</h2>
<table id="main"></table>
</body>
</html>

I got my inspiration from here: Javascript - read local text file .

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • I have added the info that is usually in the csv file, but I've named it data.csv would that make a difference if I change the csv,txt to data.csv ?. and they are all in the same directory – Andy M Aug 01 '17 at 17:12
  • Well, yes, if you use data as show in your edited post, my solution should work. Feel free to change my formatting function `tbl()` to suit your needs! My example expected tab characters (`\t`) to separate the fields. For your data use `tr.replace(/,/g,'')` instead. – Carsten Massmann Aug 01 '17 at 17:18
  • ... and of course you can name your file whatever you like. `data.csv` would be fine too! – Carsten Massmann Aug 01 '17 at 17:22
  • I've added the style to the head, but struggling with the rest. do I copy the csv.split to then split it with a "," ? give me VB any day but HTML I'm lacking a lot of knowledge. – Andy M Aug 01 '17 at 17:28
  • `csv` in my code is the name of the string variable holding the contents of your csv file. `.split('\n')` is a method of the String() prototype. It returns an array with elements split at the locations given by the string `'\n'`. I then do something with each element of that array in the `.map()` construct. I replace each occurence of `\t` with `''`and surround it by further bits to turn it into a `''` element. – Carsten Massmann Aug 01 '17 at 18:13
  • I can only assume that the companies security settings are interfering with the way this runs as i'm really struggling to get it to work. the code above is what i have used (shown in the latest edit) but still shows a blank page apart from the the H2 title – Andy M Aug 02 '17 at 10:28
  • If you are using the Internet Explorer then it is very likely that some security settings might prevent you from using JavaScript in "local" files, i. e., those addressed by `file:///c:/somedir/...`. But even for these cases you can change your security settings. In your browser look for something like "internet options -> security" and make sure JavaScript is not deactivated. Also check your console ( `` on IE) for possible warnings or messages. – Carsten Massmann Aug 02 '17 at 16:17
  • I can't even see the security tab in the Internet options which is slightly annoying, yes i'm trying to configure it for Windows 7 IE11, chrome shows a small box – Andy M Aug 03 '17 at 12:30
  • Try and contact your local IT personnel to help you with the necessary settings in your browser. Another aspect might be that the IIS (web server) only hosts file types with a defined mime type. Check, whether you can call up your CSV file in your browser. – Carsten Massmann Aug 03 '17 at 19:04
  • thank you for trying to help me, I have learnt a lot so far. I was looking at something completely different and I have found a solution but need help to tidy up. Do I add it to this question or start another one ? – Andy M Aug 14 '17 at 12:26
  • Always start a new question! And make it as short and concise as possible. --> https://stackoverflow.com/help/mcve – Carsten Massmann Aug 14 '17 at 15:04
  • I've started a new question https://stackoverflow.com/questions/45674725/change-javascript-to-generic-to-use-with-multiple-sources-csv-to-html but I have also bought a JavaScript for Dummies book to try and learn more – Andy M Aug 15 '17 at 10:43