在javascript中读取本地csv文件?

栏目: JavaScript · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/29393064/reading-in-a-local-csv-file-in-javascript
[编辑]我用 D3

解决了这个问题,谢天谢地!

所以我有一个看起来像这样的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"

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

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

但就目前而言,我只是坚持将其导入javascript.

我当前的代码如下所示:

<!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);
  }
}

我已经研究过,并在Stackoverflow上找到了一些有用的链接,如 this , thisthis ,但我是javascript的新手,我并不完全理解它.我应该使用Ajax吗?的FileReader? jQuery的?使用一个优于另一个有什么好处?你将如何在代码中实现这一点?

但是,是的,我只是困惑,因为我对javascript很新,所以任何正确方向的帮助都会很棒.谢谢!!

以下是如何使用 FileReader

API中的readAsBinaryString()来加载本地文件.

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

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

基本上,只需要在<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

翻译自:https://stackoverflow.com/questions/29393064/reading-in-a-local-csv-file-in-javascript


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Graph Theory

Introduction to Graph Theory

Douglas B. West / Prentice Hall / 2000-9-1 / USD 140.00

For undergraduate or graduate courses in Graph Theory in departments of mathematics or computer science. This text offers a comprehensive and coherent introduction to the fundamental topics of graph ......一起来看看 《Introduction to Graph Theory》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器