简体   繁体   English

如何从 csv 文件读取和显示数据到 html 网页?

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

I am new to html coding.我是 html 编码的新手。 I want to read and display my csv file data to a webpage.我想读取我的 csv 文件数据并将其显示到网页上。 Data in each row of csv file must be displayed in a separate line on webpage. csv文件每一行的数据必须在网页上单独显示。 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您可以使用以下 javascript 从 csv 文件中读取和显示数据

<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加载文档后,您可以迭代allTextLines数组

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 filename.csv应该放在你的服务器静态资源中的位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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