I have a very simple requirement but not able to figure out as to how to do it. Below Javascript code reads a CSV file and creates a HTML table. My CSV has following data in it:
Type, Item, Value, Dec, Figure
SUM,ThisItem,ThisValue,2,4
SUM,ThisItem1,ThisValue1,4,5
RCT,ThisItem1,ThisValue1,6,7
How can I insert a code or a line in below code that would help me store "Type" column value in a variable, "Item" column value in a variable and so on. For example, if Type=="SUM" then take some action (for example send data or complete row to table). I tried several times by adding some logic but to no avail.
function Upload() {
const columns = [0,1,2,3,4] // represents allowed column 1 and 3 in index form
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) { var cells = rows[i].split(","); if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
// ignore columns that are not allowed
if (!columns.includes(j)) {
continue
}
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
cells[j]is the textual data coming from the CSV file? Example:Type, Item, Value, Dec, Figure?