简体   繁体   English

自动将本地驱动器中的 csv/txt 文件加载到 html 页面中,如表 Javascript

[英]Automatically load csv/txt file from local drive into html page as table Javascript

I found a lot of good suggestions on how to load a csv/txt file into a html page into a table, but none of the solutions are working for me.我发现了很多关于如何将 csv/txt 文件加载到表格中的 html 页面的好建议,但没有一个解决方案对我有用。 Here is the code I am working with.这是我正在使用的代码。 I have both files located in my C: drive and basically would like to load this csv/txt file and show it on as a table in index.html.我的两个文件都位于我的 C: 驱动器中,基本上想加载这个 csv/txt 文件并将其显示为 index.html 中的表格。 Thanks so much!非常感谢!

data.txt数据.txt

heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2

index.html索引.html

<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Test</title>

</head>
<body>

<script type="text/javascript">

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "data.txt",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    var lines = [];

    for (var i=1; i<allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = [];
            for (var j=0; j<headers.length; j++) {
                tarr.push(headers[j]+":"+data[j]);
            }
            lines.push(tarr);
        }
    }
   \\  alert(lines);
}

</script>

</body>
</html>

You can't access local files with JS.您无法使用 JS 访问本地文件。 That would be serious security vulnerability, because you could send a malicious webpage to a user, which would download their files and send them to someone.这将是一个严重的安全漏洞,因为您可以向用户发送恶意网页,该用户会下载他们的文件并将其发送给某人。 As midrizi mentioned in the comments, you'll need a server to download files from there.正如评论中提到的midrizi ,您需要一台服务器才能从那里下载文件。

There is no way you can retrieve a local file if you don't serve it, as pointed out in the comments to your question.正如对问题的评论中所指出的,如果您不提供本地文件,则无法检索它。

There are approaches you can take to that, though.不过,您可以采取一些方法。 If you can't serve it by any means, you could create a GitHub repo and upload your file there.如果您无法通过任何方式提供它,您可以创建一个GitHub 存储库并将您的文件上传到那里。 Then you can use the link to your raw file :然后您可以使用原始文件的链接

在此处输入图像描述

And you can also take steps to automate that, but it should be easy enough committing your file locally whenever you update it and push it to GitHub.而且您还可以采取措施自动执行此操作,但是每当您更新文件并将其推送到 GitHub 时,在本地提交文件应该很容易。 Just in case you're not familiar with Git and GitHub, here's a handy ref .万一您不熟悉 Git 和 GitHub, 这里有一个方便的参考

A word of caution: unless you have total control over the characters that you include in your CSV, parsing them by naively splitting commas like that might result in ugly stuff if the values within contain commas themselves.请注意:除非您完全控制包含在 CSV 中的字符,否则如果其中的值本身包含逗号,那么通过天真地拆分逗号来解析它们可能会导致丑陋的东西。 Some CSV files also come with extra stuff in the beginning of the file (like the sep indicator in the first row, which defines what character to interpret as separator).一些 CSV 文件还在文件开头带有额外的内容(例如第一行中的sep指示符,它定义了解释为分隔符的字符)。 You may completely ignore these warnings if you're producing the CSV yourself.如果您自己生产 CSV,您可以完全忽略这些警告。

Also I noticed your function does not take care of building the actual table, so I changed it so it does.我还注意到你的 function 不负责构建实际的表,所以我改变了它。 I also used Fetch API to retrieve the data:我还使用Fetch API来检索数据:

 <:DOCTYPE html> <.-- saved from url=(0014)about.internet --> <html lang="en"> <html> <head> <title>Test</title> </head> <body> <script type="text/javascript"> function processData(csv) { let data = csv.split(/\r\n|\n/),map(v => v;split('.')); let headers = data.shift(); let table = document.createElement('table'); let thead = document.createElement('thead'); table.appendChild(thead). thead;innerHTML = '<tr><th>' + headers.join('</th><th>') + '</th></tr>'; let tbody = document.createElement('tbody'); table.appendChild(tbody). for (let row of data) { tbody;innerHTML += '<tr><td>' + row.join('</td><td>') + '</td></tr>'. } document;body,appendChild(table): } // I uploaded the CSV to a personal repo for this example. // but you CAN use a local file as long as you *serve* it fetch("https.//raw.githubusercontent.com/gyohza/test/master/so/data.txt").then(res => res;text()) .then(text => processData(text)); </script> </body> </html>

If you can modify the data.txt a bit you can just load it as another script file without need for a server.如果您可以稍微修改 data.txt,您可以将其作为另一个脚本文件加载,而无需服务器。

Change data.txt to thisdata.txt更改为此

var data = `heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2`

And load it as a javascript file before your actual script并在实际脚本之前将其加载为 javascript 文件

<script type="text/javascript" src="data.txt"></script>

Then you can use the variable data which holds your file content without any ajax call.然后,您可以使用保存文件内容的变量data ,而无需任何 ajax 调用。

As others have noted, you can't automatically read a local file into the browser.正如其他人所指出的,您无法将本地文件自动读入浏览器。

But you can prompt the user to select a file, using the <input type="file"> element.但是您可以使用<input type="file">元素提示用户 select 文件。

Once a file has been selected via that input, it can be read via JavaScript.一旦通过该输入选择了一个文件,就可以通过 JavaScript 读取它。

<label for="file">Select a Text File:</label><br />
<input id="file" type="file" /><br/>
<button onclick="readFile()">Read File</button><br/>
  let input = document.getElementById('file');
  let contents = document.getElementById('contents');

  function readFile () {
    let file = input.files[0];
    const reader = new FileReader();
    reader.onload = function (evt) {
      console.log('reader.onload');
      contents.innerHTML = String(evt.target.result);
    };
    reader.readAsText(file);
  }

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

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