gpt4 book ai didi

javascript - 如何获取csv文件的每一行

转载 作者:行者123 更新时间:2023-12-01 01:39:32 25 4
gpt4 key购买 nike

我正在尝试使用读取 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 文件。我该怎么做

最佳答案

您可以使用正则表达式将文本拆分为行,然后迭代这些行以根据需要进行输出。下面仍然需要首先下载整个文件(在解析之前),但是一旦加载,您可以将其解析为行并根据需要输出(在本例中是逐行)。使用超时来夸大此示例。

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

关于javascript - 如何获取csv文件的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52547557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com