I’m trying to upload content through csv file for that using the below given code
async uploadCSV(ev){
const reader = new FileReader();
const file = ev.target.files[0];
var file_name = file.name.split(".");
var file_ext = file_name[file_name.length - 1].toLowerCase();
if (file_ext !== "csv") {
return this.toasterServ.error("Please upload only csv file");
} else {
var output;
reader.onload = () => {
var csvToText = reader.result;
output = this.csvToJSON(csvToText);
console.log(output);
};
reader.readAsText(file);
await new Promise((f) => setTimeout(f, 2000));
this.submit();
}
}
dataSource = [];
csvToJSON(csv) {
var lines = csv.split("n");
var result = [];
var headers;
var fileType;
headers = lines[0].split(",");
headers = headers.map((s) => s.replace(/n|t|r/gm, ""), headers);
for (var i = 1; i < lines.length; i++) {
console.log("lines ---", lines);
let obj = {};
if (lines[i] == undefined || lines[i].trim() == "") {
continue;
}
var words = lines[i].split(",");
var criteria = { };
for (var j = 0; j < words.length; j++) {
let name;
let userEmail;
let userPhone='-';
let fname = headers.indexOf("First Name");
let lname = headers.indexOf("Last Name");
let emailIndex= headers.indexOf("Email");
let contactIndex= headers.indexOf("Phone");
let notes= headers.indexOf("Notes");
fname=fname != -1 ? words[fname].replace(/n|t|r/gm, "") : "";
lname=lname != -1 ? words[lname].replace(/n|t|r/gm, "") : "";
userEmail=emailIndex != -1 ? words[emailIndex].replace(/n|t|r/gm, "") : "";
/* End */
let header=headers[j];
if(header!='First Name' && header!='Last Name' && header!='Email' && header!='Phone')
{
criteria[header] = words[j];
}
obj = {
Name: name,
Email:userEmail,
};
}
result.push(obj);
}
this.dataSource = result;
console.log("datadource ", this.dataSource);
}
here issue i’m facing is if comma is there in any column then a new row is created from that point whole data gets disturbed. I want if comma is there in between the data column then also it should upload the data.If comma is not there then it is working
Any solution Thanks