How to read data From *.CSV file using javascript?

后端 未结 13 782
不知归路
不知归路 2020-11-22 00:46

My csv data looks like this:

heading1,heading2,heading3,heading4,heading5,value1_1,value2_1,value3_1,value4_1,value5_1,value1_2,value2_2,value3_2,val

13条回答
  •  北海茫月
    2020-11-22 01:27

    Don't split on commas -- it won't work for most CSV files, and this question has wayyyy too many views for the asker's kind of input data to apply to everyone. Parsing CSV is kind of scary since there's no truly official standard, and lots of delimited text writers don't consider edge cases.

    This question is old, but I believe there's a better solution now that Papa Parse is available. It's a library I wrote, with help from contributors, that parses CSV text or files. It's the only JS library I know of that supports files gigabytes in size. It also handles malformed input gracefully.

    1 GB file parsed in 1 minute: Parsed 1 GB file in 1 minute

    (Update: With Papa Parse 4, the same file took only about 30 seconds in Firefox. Papa Parse 4 is now the fastest known CSV parser for the browser.)

    Parsing text is very easy:

    var data = Papa.parse(csvString);
    

    Parsing files is also easy:

    Papa.parse(file, {
        complete: function(results) {
            console.log(results);
        }
    });
    

    Streaming files is similar (here's an example that streams a remote file):

    Papa.parse("http://example.com/bigfoo.csv", {
        download: true,
        step: function(row) {
            console.log("Row:", row.data);
        },
        complete: function() {
            console.log("All done!");
        }
    });
    

    If your web page locks up during parsing, Papa can use web workers to keep your web site reactive.

    Papa can auto-detect delimiters and match values up with header columns, if a header row is present. It can also turn numeric values into actual number types. It appropriately parses line breaks and quotes and other weird situations, and even handles malformed input as robustly as possible. I've drawn on inspiration from existing libraries to make Papa, so props to other JS implementations.

提交回复
热议问题