简体   繁体   English

Javascript将CSV文件加载到数组中

[英]Javascript loading CSV file into an array

I am developing a web page in Wordpress. 我正在使用Wordpress开发一个网页。 The webpage needs to have a combobox with all counties. 网页需要有一个与所有县组合的组合框。 I have a dataset in csv format which has some 10k rows for all these counties. 我有一个csv格式的数据集,对于所有这些县都有大约10k行。 When the user selects a county in the dropdown, I want only the selected county data displayed in the web page. 当用户在下拉列表中选择一个县时,我只想要在网页中显示所选的县数据。 This is my requirement. 这是我的要求。

In wordpress, my web page I am adding the js file using 在wordpress,我的网页我正在使用js文件添加

<script type="text/javascript" src="http://xxx/wp     content/uploads/2014/05/countyList1.js"></script>

and the code for webpage dropdown is 并且网页下拉的代码是

<select name="county" id="county" onload="setCounties();" onchange="getSelectedCountyData();"></select>

In countyList1.js file I have the setCounties() and getSelectedCountyData() functions. 在countyList1.js文件中,我有setCounties()和getSelectedCountyData()函数。

So far I can see the dropdown with counties list. 到目前为止,我可以看到与县列表的下拉列表。 I don't know how to read the CSV file and apply the selected county filter to this list. 我不知道如何阅读CSV文件并将选定的县过滤器应用于此列表。

I tried the FileReader object and I can load the CSV contents on the web page but I don't want the user to select the CSV. 我尝试了FileReader对象,我可以在网页上加载CSV内容,但我不希望用户选择CSV。 I have the dataset already. 我已经有了数据集。

I am trying to use this jquery.csv-0.71 library from this SO post How to read data From *.CSV file using javascript? 我正在尝试使用此SO帖子中的这个jquery.csv-0.71库如何使用javascript从* .CSV文件读取数据? but I need help. 但我需要帮助。

Here's the code which gets called when a county is selected 这是在选择县时调用的代码

function getSelectedCountyData() {
        cntrySel = document.getElementById('county');
        //selCty = countyList[cntrySel.value];
        handleFiles();
}

function handleFiles() {

    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "D:\Docs\Desktop\csvfile.csv",
            dataType: "csv",
            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);
        }
    }
    console.log(lines);
    drawOutput(lines);
}

function drawOutput(lines) {
    //Clear previous data
    document.getElementById("output").innerHTML = "";
    var table = document.createElement("table");
    for (var i = 0; i < lines.length; i++) {
        var row = table.insertRow(-1);
        for (var j = 0; j < lines[i].length; j++) {
            var firstNameCell = row.insertCell(-1);
            firstNameCell.appendChild(document.createTextNode(lines[i][j]));
        }
    }
    document.getElementById("output").appendChild(table);
}

I highly recommend looking into this plugin: 我强烈建议您查看此插件:

http://github.com/evanplaice/jquery-csv/ http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. 我将它用于处理大型CSV文件的项目,它可以很好地将CSV解析为数组。 You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload. 您也可以使用它来调用您在代码中指定的本地文件,这样您就不依赖于文件上载。

Once you include the plugin above, you can essentially parse the CSV using the following: 上面包含插件后,您可以使用以下方法解析CSV:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. 然后,所有内容都将存在于数组数据中,供您根据需要进行操作。 I can provide further examples for handling the array data if you need. 如果需要,我可以提供处理数组数据的更多示例。

There are a lot of great examples available on the plugin page to do a variety of things, too. 插件页面上有很多很好的例子可以用来做各种各样的事情。

If your not overly worried about the size of the file then it may be easier for you to store the data as a JS object in another file and import it in your . 如果您并不过分担心文件的大小,那么您可能更容易将数据作为JS对象存储在另一个文件中并将其导入到您的文件中。 Either synchronously or asynchronously using the syntax <script src="countries.js" async></script> . 使用语法<script src="countries.js" async></script>同步或异步。 Saves on you needing to import the file and parse it. 保存您需要导入文件并解析它。

However, i can see why you wouldnt want to rewrite 10000 entries so here's a basic object orientated csv parser i wrote. 但是,我可以看到为什么你不想重写10000个条目所以这里是我写的一个基本的面向对象的csv解析器。

function requestCSV(f,c){return new CSVAJAX(f,c);};
function CSVAJAX(filepath,callback)
{
    this.request = new XMLHttpRequest();
    this.request.timeout = 10000;
    this.request.open("GET", filepath, true);
    this.request.parent = this;
    this.callback = callback;
    this.request.onload = function() 
    {
        var d = this.response.split('\n'); /*1st separator*/
        var i = d.length;
        while(i--)
        {
            if(d[i] !== "")
                d[i] = d[i].split(','); /*2nd separator*/
            else
                d.splice(i,1);
        }
        this.parent.response = d;
        if(typeof this.parent.callback !== "undefined")
            this.parent.callback(d);
    };
    this.request.send();
};

Which can be used like this; 哪个可以这样使用;

var foo = requestCSV("csvfile.csv",drawlines(lines)); 

The first parameter is the file, relative to the position of your html file in this case. 第一个参数是文件,相对于此情况下html文件的位置。 The second parameter is an optional callback function the runs when the file has been completely loaded. 第二个参数是一个可选的回调函数,它在文件完全加载时运行。

If your file has non-separating commmas then it wont get on with this, as it just creates 2d arrays by chopping at returns and commas. 如果你的文件有非分离的commma,那么它就不会继续使用它,因为它只是通过切换返回和逗号来创建2d数组。 You might want to look into regexp if you need that functionality. 如果需要该功能,您可能需要查看正则表达式。

//THIS works 

"1234","ABCD" \n
"!@£$" \n

//Gives you 
[
 [
  1234,
  'ABCD'
 ],
 [
  '!@£$'
 ]
]

//This DOESN'T!

"12,34","AB,CD" \n
"!@,£$" \n

//Gives you

[
 [
  '"12',
  '34"',
  '"AB',
  'CD'
 ]
 [
  '"!@',
  '£$'
 ]
]

If your not used to the OO methods; 如果你不习惯OO方法; they create a new object (like a number, string, array) with their own local functions and variables via a 'constructor' function. 他们通过'构造函数'函数创建一个具有自己的本地函数和变量的新对象(如数字,字符串,数组)。 Very handy in certain situations. 在某些情况下非常方便。 This function could be used to load 10 different files with different callbacks all at the same time(depending on your level of csv love! ) 此功能可用于同时加载10个具有不同回调的不同文件(取决于您对csv的爱程度!)

You can't use AJAX to fetch files from the user machine. 您无法使用AJAX从用户计算机获取文件。 This is absolutely the wrong way to go about it. 这绝对是错误的做法。

Use the FileReader API: 使用FileReader API:

<input type="file" id="file input">

js: JS:

console.log(document.getElementById("file input").files); // list of File objects

var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);

Then parse content as CSV. 然后将content解析为CSV。 Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4""" 请记住,您的解析器当前不处理CSV中的转义值,如: value1,value2,"value 3","value ""4"""

This is what I used to use a csv file into an array. 这就是我以前将csv文件用于数组的过程。 Couldn't get the above answers to work, but this worked for me. 无法得到上述答案,但这对我有用。

$(document).ready(function() {
   "use strict";
    $.ajax({
        type: "GET",
        url: "../files/icd10List.csv",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(icd10Codes) {
    "use strict";
    var input = $.csv.toArrays(icd10Codes);
    $("#test").append(input);
}

Used the jQuery-CSV Plug-in linked above. 使用上面链接的jQuery-CSV插件。

原始代码适用于读取和分离csv文件数据,但您需要将数据类型从csv更改为文本。

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

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