在 javascript 中读取本地 csv 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29393064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:17:24  来源:igfitidea点击:

Reading in a local csv file in javascript?

javascriptjqueryajaxcsvfilereader

提问by ocean800

[EDIT]I solved the problem using D3, nevermind thanks!

[编辑]我使用D3解决了这个问题,没关系,谢谢!

So I have a csv file that looks something like this, and I need to import a local csv file into my client side javascript:

所以我有一个看起来像这样的 csv 文件,我需要将本地 csv 文件导入到我的客户端 javascript 中:

    "L.Name", "F.Name", "Gender", "School Type", "Subjects"
    "Doe",    "John",  "M",      "University",  "Chem I, statistics, English, Anatomy"
    "Tan",    "Betty",   "F",     "High School", "Algebra I, chem I, English 101"
    "Han",    "Anna",    "F",     "University",  "PHY 3, Calc 2, anatomy I, spanish 101"
    "Hawk",   "Alan",    "M",     "University",  "English 101, chem I" 

I eventually need do parse it and output something like:

我最终需要解析它并输出如下内容:

Chem I: 3         (number of people taking each subject)
Spanish 101: 1 
Philosophy 204: 0 

But for now, I am stuck on just importing it into javascript.

但就目前而言,我只是将它导入到 javascript 中。

My current code looks like this:

我当前的代码如下所示:

<!DOCTYPE html>  
<html>  
<body>
<h1>Title!</h1>
<p>Please enter the subject(s) that you wish to search for:</p>
<input id="numb" type="text"/> 
<button onclick="myFunction()">Click me to see! :) </button>
<script>
function myFunction() {
    var splitResearchArea = []; 
    var textInput = document.getElementById('numb').value; 
    var splitTextInput = textInput.split(",");

  for(var i =0; i<splitTextInput.length; i++) {
    var spltResearchArea = splitTextInput[i];
    splitResearchArea.push(spltResearchArea);
  }
}

I've researched and found some helpful links on Stackoverflow like this, this, and thisbut I'm new to javascript and I don't completely understand it. Should I use Ajax? FileReader? jQuery? What are the benefits of using one over the other? And how would you implement this in code?

我已经研究并在 Stackoverflow 上找到了一些有用的链接,例如thisthisthis但我是 javascript 新手,我并不完全理解它。我应该使用 Ajax 吗?文件阅读器?jQuery?使用一个比另一个有什么好处?你将如何在代码中实现这一点?

But yeah, I'm just confused since I'm very new to javascript, so any help in the right direction would be great. Thank you!!

但是,是的,我很困惑,因为我对 javascript 还很陌生,所以在正确方向上的任何帮助都会很棒。谢谢!!

回答by Jose Rui Santos

Here is how to use the readAsBinaryString()from the FileReaderAPI to load a local file.

下面是如何使用readAsBinaryString()的FileReaderAPI来加载本地文件。

<p>Select local CSV File:</p>
<input id="csv" type="file">

<output id="out">
    file contents will appear here
</output>

Basically, just need to listen to change event in <input type="file">and call the readFile function.

基本上,只需要监听更改事件<input type="file">并调用 readFile 函数。

var fileInput = document.getElementById("csv"),

    readFile = function () {
        var reader = new FileReader();
        reader.onload = function () {
            document.getElementById('out').innerHTML = reader.result;
        };
        // start reading the file. When it is done, calls the onload event defined above.
        reader.readAsBinaryString(fileInput.files[0]);
    };

fileInput.addEventListener('change', readFile);

jsFiddle

js小提琴

回答by Legendary

i use this library from google: https://github.com/evanplaice/jquery-csv/First - u have to

我使用谷歌的这个库:https: //github.com/evanplaice/jquery-csv/首先 - 你必须

$.get(ur_csv_file_path);

and then use guide from page

然后使用页面中的指南

回答by Vivian River

There are as many ways of accomplishing what you want as you could possibly imagine.

有许多方法可以实现您想要的一切。

If I were doing this, I might start by splitting the input text into lines like so:

如果我这样做,我可能首先将输入文本分成如下几行:

var lines = inputText.split('\n');

Then, I would extract the names of the headers from the first line. You need a function to read the values from each line.

然后,我将从第一行中提取标题的名称。您需要一个函数来读取每一行的值。

// This assumes no commas in the values names.
function getCsvValuesFromLine(line) {
    var values = lines[0].split(',');
    value = values.map(function(value){
        return value.replace(/\"/g, '');
    });
    return values;
}

var headers = getCsvValuesFromLine(lines[0]);

Next, I would loop over the remaining lines and create an array of objects representing the values in the lines.

接下来,我将遍历剩余的行并创建一个表示行中值的对象数组。

lines.shift(); // remove header line from array
var people = lines.map(function(line) {
    var person = {},
        lineValues = getCsvValuesFromLine(line);
    for(var i = 0; i < lines.length; i += 1) {
        person[headers[i]] = lineValues[i];
    }
    return person;
});

If this all works, you should end up with an array of objects representing the values in each line in your CSV.

如果这一切正常,您应该最终得到一个对象数组,表示 CSV 中每一行中的值。



The above is a rough outline of what the code might look like. I have not tested it and it certainly is not production ready, but I hope it gives you an idea of how to go about doing what you want.

以上是代码外观的粗略概述。我还没有测试过它,它肯定还没有准备好生产,但我希望它能让你知道如何去做你想做的事。

I've used several built-in Javascript functions. I suggest looking them up on MDN if you're not familiar with them; they are good to know.

我使用了几个内置的 Javascript 函数。如果您不熟悉它们,我建议您在 MDN 上查找它们;他们很高兴知道。

Finally, there is an odd quirk in Javascript with its automatic semi-colon insertion (a bad feature of the language, IMO). In order to avoid problems, do not put a new-line before an opening brace.

最后,Javascript 有一个奇怪的怪癖,它的自动分号插入(该语言的一个坏特性,IMO)。为避免出现问题,请勿在左大括号前放置换行符。

Always write

总是写

XXXX {
    ....
}

and don't write

不要写

XXXX
{
    ....
}