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 文件。我怎么做
解决方案
您可以在打印之前将其读取并写入数组。
$(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);
}
推荐阅读
- javascript - 如何制作下拉类型菜单?
- android - 使用 wikipedia api 获取我的 android 应用程序的随机文章
- linux - 以非root用户身份在linux中列出目录内容
- flutter - 颤动多行文本字段光标移动到键盘下方
- css - CSS选择具有可变div ID的二等孩子
- jquery - 如何根据表格操作列中的用户角色使编辑和删除按钮可见或不可见?
- python - 从函数中删除全局变量
- django - Django defer() 和 only() 查询集不起作用?
- reactjs - 在第二次 onChange 后反应更新状态
- python - 检查链接中的短语是否以数字开头,然后是带有 beautifullsoup 的字母