How to read a csv file on angular2 line by line
In addition to asmmahmud's answer, I'd like to add how you can actually parse the file content so you have rows and columns in an array (Angular with TypeScript). Add the property:
parsedCsv: string[][];
to the class YourComponent
in his example.
Then, update the onFileLoad
event as follows:
onFileLoad(fileLoadedEvent): void {
const csvSeparator = ';';
const textFromFileLoaded = fileLoadedEvent.target.result;
this.csvContent = textFromFileLoaded;
// alert(textFromFileLoaded);
const txt = textFromFileLoaded;
const csv = [];
const lines = txt.split('\n');
lines.forEach(element => {
const cols: string[] = element.split(csvSeparator);
csv.push(cols);
});
this.parsedCsv = csv;
// console.log(this.parsedCsv);
}
Now you have the parsed CSV with its lines and columns in the two-dimensional array parsedCsv
(1st dimension is the rows, 2nd dimension the column). You can replace the separator if required - default is semicolon.
Example:
A file containing
A;B;C
1;2,300;3
4;5.5;6
produces the following data structure in parsedCsv
You can see that if your file contains column headers, then the data starts with row index 1, otherwise (without column headers) with row index 0.
Updated Stackblitz Example
Note: On Stackblitz, I have added the following few lines so you can see how the array is populated:
// demo output as alert
var output: string="";
csv.forEach(row => {
output += "\n";
var colNo = 0;
row.forEach(col => {
if (colNo>0) output += " | ";
output += col;
colNo++;
});
});
alert(output);
Here is a example implementation angular way (Angular version 2+):
@Component({
selector: 'app-my-file',
template: `
<div class="form-group">
<input type="file" (change)="onFileSelect($event.target)" name="myfile">
</div>
`,
styles: [``]
})
export class YourComponent implements OnInit {
csvContent: string;
constructor(){}
ngOnInit(){
}
onFileLoad(fileLoadedEvent) {
const textFromFileLoaded = fileLoadedEvent.target.result;
this.csvContent = textFromFileLoaded;
// alert(this.csvContent);
}
onFileSelect(input: HTMLInputElement) {
const files = input.files;
var content = this.csvContent;
if (files && files.length) {
/*
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
*/
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.readAsText(fileToLoad, "UTF-8");
}
}
}
Try it on StackBlitz
csv2Array(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: string = reader.result;
let allTextLines = csv.split(/\r|\n|\r/);
let headers = allTextLines[0].split(',');
let lines = [];
for (let i = 0; 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);
} }