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

后端 未结 13 788
不知归路
不知归路 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:25

    NOTE: I concocted this solution before I was reminded about all the "special cases" that can occur in a valid CSV file, like escaped quotes. I'm leaving my answer for those who want something quick and dirty, but I recommend Evan's answer for accuracy.


    This code will work when your data.txt file is one long string of comma-separated entries, with no newlines:

    data.txt:

     heading1,heading2,heading3,heading4,heading5,value1_1,...,value5_2
    

    javascript:

    $(document).ready(function() {
        $.ajax({
            type: "GET",
            url: "data.txt",
            dataType: "text",
            success: function(data) {processData(data);}
         });
    });
    
    function processData(allText) {
        var record_num = 5;  // or however many elements there are in each row
        var allTextLines = allText.split(/\r\n|\n/);
        var entries = allTextLines[0].split(',');
        var lines = [];
    
        var headings = entries.splice(0,record_num);
        while (entries.length>0) {
            var tarr = [];
            for (var j=0; j

    The following code will work on a "true" CSV file with linebreaks between each set of records:

    data.txt:

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

    javascript:

    $(document).ready(function() {
        $.ajax({
            type: "GET",
            url: "data.txt",
            dataType: "text",
            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

    http://jsfiddle.net/mblase75/dcqxr/

提交回复
热议问题