Reading in a local csv file in javascript? [closed]

狂风中的少年 提交于 2019-12-02 16:51:55

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

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

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

Legendary

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

$.get(ur_csv_file_path);

and then use guide from page

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.


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.

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.

Always write

XXXX {
    ....
}

and don't write

XXXX
{
    ....
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!