NG8- Validation - upload header columns order in Angular
========================================================
component.ts:
===================
fileReaded;
arrIndex;
onFileSelect(fileInput: any){
//read file from input
this.fileReaded = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.readAsText(this.fileReaded);
reader.onload = (e) => {
let csv: any = reader.result;
let headers;
let allTextLines = csv.split(/\r|\n|\r/);
//col_ord1|col_ord2|col_ord3|col_ord4|col_ord5|col_ord6
let checkHeader = [ "col_ord1|col_ord2|col_ord3|col_ord4|col_ord5|col_ord6", "", ""]
for (let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
//console.log(data)
var c= checkHeader.filter(checkHeader => !data.includes(checkHeader));
if(c.length == 0){
headers=allTextLines[i].split(',');
this.arrIndex = i+1;
console.log('header matchecd');
break;
}
else{
console.log('header doesnt matchec');
}
}
let lines = [];
for (let i = this.arrIndex; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length === headers.length) {
let tarr = [];
for (let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
// log each row to see output
console.log(tarr);
lines.push(tarr);
}
}
// all rows in the csv file
// console.log(">>>>>>>>>>>>>>>>>", lines);
}
}
template.html
==============
<div class="form-group">
<input type="file" (change)="onFileSelect($event)" name="myfile">
</div>
========================================================
component.ts:
===================
fileReaded;
arrIndex;
onFileSelect(fileInput: any){
//read file from input
this.fileReaded = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.readAsText(this.fileReaded);
reader.onload = (e) => {
let csv: any = reader.result;
let headers;
let allTextLines = csv.split(/\r|\n|\r/);
//col_ord1|col_ord2|col_ord3|col_ord4|col_ord5|col_ord6
let checkHeader = [ "col_ord1|col_ord2|col_ord3|col_ord4|col_ord5|col_ord6", "", ""]
for (let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
//console.log(data)
var c= checkHeader.filter(checkHeader => !data.includes(checkHeader));
if(c.length == 0){
headers=allTextLines[i].split(',');
this.arrIndex = i+1;
console.log('header matchecd');
break;
}
else{
console.log('header doesnt matchec');
}
}
let lines = [];
for (let i = this.arrIndex; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length === headers.length) {
let tarr = [];
for (let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
// log each row to see output
console.log(tarr);
lines.push(tarr);
}
}
// all rows in the csv file
// console.log(">>>>>>>>>>>>>>>>>", lines);
}
}
template.html
==============
<div class="form-group">
<input type="file" (change)="onFileSelect($event)" name="myfile">
</div>
No comments:
Post a Comment