首页 > 解决方案 > 如何获取csv文件的每一行

问题描述

我正在尝试使用下面的代码读取 csv 文件

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);
<p>Select local CSV File:</p>
<input id="csv" type="file">
    
<output id="out">
    file contents will appear here
</output>

它工作正常,但我需要一一打印每一行,而不仅仅是一次打印整个 csv 文件。我怎么做

标签: javascriptcsv

解决方案


您可以在打印之前将其读取并写入数组。

$(document).ready(function() {
$.ajax({
    type: "GET",
    url: "data.csv",
    dataType: "text",
    success: function(data) {readdata(data);}
 });
});

function readdata(textCsv) {
var record_num = 5;  // how many elements there are in each row
var allCsvLines = textCsv.split(/\r\n|\n/);
var entries = allCsvLines[0].split(',');
var lines = [];
var headings = entries.splice(0,record_num);
while (entries.length>0) {
    var tarr = [];
    for (var j=0; j<record_num; j++) {
        tarr.push(headings[j]+":"+entries.shift());
    }
    lines.push(tarr);
}
alert(lines);
}

推荐阅读