简体   繁体   中英

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. 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. Thanks so much!

data.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

<!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. 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.

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. 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. Just in case you're not familiar with Git and GitHub, here's a handy ref .

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. 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). You may completely ignore these warnings if you're producing the CSV yourself.

Also I noticed your function does not take care of building the actual table, so I changed it so it does. I also used Fetch API to retrieve the data:

 <: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.

Change data.txt to this

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

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

Then you can use the variable data which holds your file content without any ajax call.

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.

Once a file has been selected via that input, it can be read via 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);
  }

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