I am able to display the content from a csv file on a web page ( based on what I have found on this site), but how do I read the csv values into an array in JavaScript?
Let's say if I have a file in this CSV format:
Red, Green, Blue,,
Orange, Yellow, Black,,
Indigo, purple, navy,, ...
I appreciate any help.
-
Perhaps you can try github.com/mholt/PapaParseslider– slider2018年11月11日 03:28:39 +00:00Commented Nov 11, 2018 at 3:28
-
I deleted my earlier comments. I am able to see an Array for each line of my csv file using Papa Parse. I had to click on the small triangles to expand. I don't know how to console.log to see the Arrays again.Dataman– Dataman2018年11月25日 04:42:35 +00:00Commented Nov 25, 2018 at 4:42
1 Answer 1
function UploadCSV() {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
try{
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split("|");
if (cells.length > 1) {
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
var td = cells[j].replace(/[^\x00-\x7F]/g, "");
cell.text(td);
row.append(cell);
}
table.append(row);
}
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
catch(e)
{
$('#meessageBar1').text(e.message);
$('#meessageBar1').fadeIn("slow", function () {
setTimeout(messageBar1Remove, 2000);
});
}
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
$('#meessageBar1').text('This browser does not support HTML5.');
$('#meessageBar1').fadeIn("slow", function () {
setTimeout(messageBar1Remove, 2000);
});
}
}
}
This is a snippet I used to read data from a PIPE ('|') seperated csv file data into HTML table, you can var cells = rows[i].split("|"); change this line whatever your csv file use as seperator. Here I attach each cell data of each row into of a table row, you can omit this and simply insert whole data into an array. If this helps you, please mark it as accepted answer. Thank you.