如何获取CSV文件的每一行

时间:2018-09-28 02:41:14

标签: javascript 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文件。我该怎么做

4 个答案:

答案 0 :(得分:1)

您可以在打印之前将其读写到阵列中。

$(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);
}

答案 1 :(得分:1)

您可以使用正则表达式将文本分成几行,然后遍历这些行以根据需要输出。以下内容仍然要求首先下载整个文件(在解析之前),但是一旦加载,您就可以将其解析成几行,然后根据需要输出(在这种情况下是逐行输出)。超时是用来夸大此示例的。

// Create a delay using a promise
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

var fileInput = document.getElementById("csv"),

  readFile = function() {
    var reader = new FileReader();

    reader.onload = function() {
      let lines = reader.result.split(/[\r\n]+/g)
      let output = document.querySelector('#out')

      const loop = async (lines,output) => {
        for(let line of lines) {
          await delay(333)
          output.innerHTML += line + '<br>'
        }
      }
      loop(lines,output)
    };
    // 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>

答案 2 :(得分:0)

有一种文件读取器 readAsText 的方法。它将起作用

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

答案 3 :(得分:0)

如果您想使用流来处理非常大的文件,则

// Simulate a file from input[type=file]
var csv = new Blob([
`apple,1,$1.00
banana,4,$0.20
orange,3,$0.79`])

// Use a fetch-Response hack to transform a file/blob into a stream
var stream = new Response(csv).body

var lines = 0
var stdout = new WritableStream({
  write (line, controller) {
    out.insertAdjacentText('beforeend', line)
    out.insertAdjacentHTML('beforeend', '<br>')
    
    lines++

    // Don't want to output to many lines, so we
    // abort the reading for the rest of the file
    if (lines >= 2) controller.close() 
  }
})

stream
  .pipeThrough(new TextDecoderStream()) // polyfill
  .pipeThrough(new ByLineStream())
  .pipeTo(stdout)
  
<script src="https://rawgit.com/GoogleChromeLabs/text-encode-transform-polyfill/master/text-encode-transform.js"></script>
<script src="https://rawgit.com/jimmywarting/web-byline/master/index.js"></script> 


<output id="out">
  file contents will appear here<br>
</output>