简体   繁体   中英

How to read and display data from a csv file to html webpage?

I am new to html coding. I want to read and display my csv file data to a webpage. Data in each row of csv file must be displayed in a separate line on webpage. My current code doesn't display anything and I don't have any clue why is it not working properly. Please help me in this regard. My code is below:

    <!DOCTYPE html>
<html>
<script type="text/javascript">
    var allText =[];
    var allTextLines = [];
    var Lines = [];

    var txtFile = new XMLHttpRequest();
    txtFile.open("GET", "D:\PycharmProjects\filename.csv", true);
    txtFile.onreadystatechange = function()
    {
        allText = txtFile.responseText;
        allTextLines = allText.split(/\r\n|\n/);
    };

    document.write(allTextLines);<br>
    document.write(allText);<br>
    document.write(txtFile);<br>
</script> 

You can use following javascript for read and display data from csv file

<script type="text/javascript">
$.get('/file-path/demo.csv', function(data) {
var build = '<table border="1" cellpadding="2" cellspacing="0" style="border-collapse: collapse" width="100%">\n';
var head = data.split("\n");
for(var i=0;i<1;i++){
build += "<tr><th>" + head[i] + "</th></tr>";
for(var i=1;i<head.length;i++){
build += "<tr><td>" + head[i].split("\n") + "</td></tr>";
}
}
build += "</table>";
$('#wrap').append(build);
});
</script>

You can iterate over the allTextLines array as soon as your document is loaded

var txtFile = new XMLHttpRequest();
txtFile.onload = function() {
    allText = txtFile.responseText;
    allTextLines = allText.split(/\r\n|\n/);

    for(var i = 0; i < allTextLines.length; i++) {
        document.body.innerHTML += allTextLines[i];
        document.body.innerHTML += '<br/>';
    }
}

txtFile.open("get", "filename.csv", true);
txtFile.send();

where filename.csv should be put in your server static resources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM