Roy Davies Roy Davies -4 years ago 113
HTML Question

Display CSV file in HTML

I'm trying to import a local CSV file with headings into a local HTML file, which will then display as a table in a browser.

I haven't been learning HTMLand JavaScript for long, so I don't know a lot about importing and converting. What I need is some advice or possibly a basic script describing the sort of function I need. Explanations and advice are all welcomed!

This is an example of the csv file:

heading1,heading2,heading3,heading4,heading5
value1_1,value1_2,value1_3,value1_4,value1_5
value2_1,value2_2,value2_3,value2_4,value2_5
value3_1,value3_2,value3_3,value3_4,value3_5
value4_1,value4_2,value4_3,value4_4,value4_5
value5_1,value5_2,value5_3,value5_4,value5_5


This is how I'd want to display it:

http://jsfiddle.net/yekdkdLm

Answer Source

Fetch an external file.

You have to use xmlHttpRequest for this. Simplified using jQuery (include jQuery library) as.

You will need to run the HTML file in a local server like Apache, browsers like Chrome doesnt allow xmlHttp for file:// urls.

  $.ajax({
    type: "GET",
    url: "words.txt",
    dataType: "text",
    success: parseTxt
  });

Use a success callback to process the data

parseTxt is the function to which the content of the file is read and passed. You can then write the code in parseTxt to process the text as string.

function parseTxt(text){
  var rows=text.split('\n');

  //for each row
  //cols=rows[i].split(',');
}

This should be enough to get you started I guess.


How to read a text file from server using JavaScript?

You can even try the answer to above question by Shadow Wizard using iframes.


A RAW XMLHttpRequest can be made without jQuery as shown here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download