我使用代码
读取了一个csv文件var x="dema.csv";
loadCSV(x);
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(request.responseText);
}
我使用此代码将数据放入dataObject
function parseCSV(data, dataArray) {
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// loop through all rows
for (var i = 0; i < rows.length; i++) {
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
var date=column[0];
var value = column[4];
var dataObject = {
date: date,
T4: value
};
/
dataArray.push(dataObject);
}
}
}
我只获得日期列和T4列。我的问题是,我想某种方式做一些处理(循环验证一些条件(例如:T4不应超过700超过30秒)) 我可以只使用dataObject或使用2D数组吗?如何使用正确的工具获取单元格内容?
答案 0 :(得分:1)
var x = "dema.csv";
var dataArray = [];
loadCSV(x);
function loadCSV(x) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
parseCSV(this.responseText, dataArray);
// you can loop over the array like this
//dataArray.forEach((line) => {
// here line contains data, time, tops, cycle, T4, test
// you can access them like line.time, line.T4, line.tops etc
// console.log(line.time);
// console.log(line.tops);
// etc
//});
window.alert(dataArray[0].T4);
}
};
xhttp.open("GET", x, true);
xhttp.send();
}
function parseCSV(data, arr) {
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// loop through all rows
for (var i = 0; i < rows.length; i++) {
// this line helps to skip empty rows
if (rows[i] && i > 0) {
// our columns are separated by comma
var column = rows[i].split(",");
var dataObject = mapValuesToObj(column);
arr.push(dataObject);
}
}
}
function mapValuesToObj(csvLine) {
var absTime = csvLine[0];
var time = csvLine[1];
var tops = csvLine[2];
var cycle = csvLine[3];
var t4 = csvLine[4];
var test = csvLine[5];
return {
date: absTime,
time: time,
tops: tops,
cycle: cycle,
T4: t4,
test: test
};
}