How to import CSV File in Angular

create new angular instance using below command

ng new csv-upload

Past the below code in your .html file

<input type=”file” #fileImportInput name=”File Upload” id=”txtFileUpload” (change)=”fileChangeListener($event)” accept=”.csv” />
<table>
<tr *ngFor=”let item of csvRecords”>
<td *ngFor=”let single of item”>{{single}}</td>
</tr>
</table>

add this line is in your .ts file

@ViewChild(‘fileImportInput’) fileImportInput: any;

Create a function for read the file

fileChangeListener($event: any): void {

//=============== write our code ======================

}

Check the given file is .csv or not

 var files = $event.srcElement.files;    

if (files[0].name.endsWith(‘.csv’)) {

//======== write your code ============

}else{
  alert(‘Please import valid .csv file.’);
  this.fileImportInput.nativeElement.value = ”;

}

Create an object for a reader and read the file

var input = $event.target;      

var reader = new FileReader();      

reader.readAsText(input.files[0]);
reader.onload = (data) => {

//====== we got string data we need to split that data into object====

}

Split the “,” separated data and push to our object

let csvData = reader.result;        

let csvRecordsArray = (csvData as string).split(/\r\n|\n/);

for(let i=0;i<csvRecordsArray.length;i++){

let rowdata = csvRecordsArray[i].match(/(“[^”]*”)|[^,]+/g);

this.csvRecords.push(rowdata);

}

Full .ts file code:


public csvRecords: any[] = [];
@ViewChild(‘fileImportInput’) fileImportInput: any;
  fileChangeListener($event: any): void {
    var files = $event.srcElement.files;
    if (files[0].name.endsWith(‘.csv’)) {
      var input = $event.target;
      var reader = new FileReader();
      reader.readAsText(input.files[0]);
      reader.onload = (data) => {
        let csvData = reader.result;
        let csvRecordsArray = (csvData as string).split(/\r\n|\n/);
for(let i=0;i<csvRecordsArray.length;i++){
let rowdata = csvRecordsArray[i].match(/(“[^”]*”)|[^,]+/g);
this.csvRecords.push(rowdata);
}
      };
reader.onerror = function() {
        alert(‘Unable to read ‘ + input.files[0]);
      };
    } else {
      alert(‘Please import valid .csv file.’);
      this.fileImportInput.nativeElement.value = ”;
     this.csvRecords = [];
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: