Read CSV File In Angular 7

Introduction

 
There are lots of CSV reader libraries available for Angular 7 but we will read CSV files without any library in this article and will upload a CSV file from the UI rather than a static path or source, in order to make it dynamic.
 
Prerequisites
  • Basic knowledge of Angular 7
  • Visual Studio Code
  • Angular CLI must be installed
  • NodeJS must be installed
Let’s get started.
 
Open Visual Studio Code and open a new terminal.
 
 
Type the following command in it.
  1. ng new Angular7-readCSV 
 Go to the Root folder, select "Yes" for Angular routing, and use CSS for the stylesheet.
 
  
Open the project in Visual Studio Code by opening the folder by command.
  1. code .  
 
Create one new file, namely "CSVRecord" in the app folder and paste the below code. 
  1. export class CSVRecord {  
  2.     public id: any;  
  3.     public firstName: any;  
  4.     public lastName: any;  
  5.     public age: any;  
  6.     public position: any;  
  7.     public mobile: any;     
  8.   }   
 
Open the "app.component.html" file to and paste the below HTML code.
 
 
  1. <input type="file" #csvReader name="Upload CSV" id="txtFileUpload" (change)="uploadListener($event)" accept=".csv" />    
  2. <table class="minimalistBlack" *ngIf="records.length > 0">    
  3.   <thead>    
  4.     <tr>    
  5.       <th>ID </th>    
  6.       <th>FirstName </th>    
  7.       <th>LastName </th>    
  8.       <th>Age </th>    
  9.       <th>Position </th>    
  10.       <th>Mobile </th>    
  11.     </tr>    
  12.   </thead>    
  13.   <tbody>    
  14.     <tr *ngFor="let record of records;let i = index;">    
  15.       <td> <span>{{record.id}}</span> </td>    
  16.       <td> <span>{{record.firstName}}</span> </td>    
  17.       <td> <span>{{record.lastName}}</span> </td>    
  18.       <td> <span>{{record.age}}</span> </td>    
  19.       <td> <span>{{record.position}}</span> </td>    
  20.       <td> <span>{{record.mobile}}</span> </td>    
  21.     </tr>    
  22.   </tbody>    
  23. </table>      
Now, open the "app.component.ts" file to write our main logic which reads the CSV file and generates the file data in the table.
 
  1. import { Component, ViewChild } from '@angular/core';  
  2. import { CSVRecord } from './CSVModel';  
  3.   
  4. @Component({  
  5.   selector: 'app-root',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.css']  
  8. })  
  9.   
  10. export class AppComponent {  
  11.   title = 'Angular7-readCSV';  
  12.   
  13.   public records: any[] = [];  
  14.   @ViewChild('csvReader') csvReader: any;  
  15.   
  16.   uploadListener($event: any): void {  
  17.   
  18.     let text = [];  
  19.     let files = $event.srcElement.files;  
  20.   
  21.     if (this.isValidCSVFile(files[0])) {  
  22.   
  23.       let input = $event.target;  
  24.       let reader = new FileReader();  
  25.       reader.readAsText(input.files[0]);  
  26.   
  27.       reader.onload = () => {  
  28.         let csvData = reader.result;  
  29.         let csvRecordsArray = (<string>csvData).split(/\r\n|\n/);  
  30.   
  31.         let headersRow = this.getHeaderArray(csvRecordsArray);  
  32.   
  33.         this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);  
  34.       };  
  35.   
  36.       reader.onerror = function () {  
  37.         console.log('error is occured while reading file!');  
  38.       };  
  39.   
  40.     } else {  
  41.       alert("Please import valid .csv file.");  
  42.       this.fileReset();  
  43.     }  
  44.   }  
  45.   
  46.   getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {  
  47.     let csvArr = [];  
  48.   
  49.     for (let i = 1; i < csvRecordsArray.length; i++) {  
  50.       let curruntRecord = (<string>csvRecordsArray[i]).split(',');  
  51.       if (curruntRecord.length == headerLength) {  
  52.         let csvRecord: CSVRecord = new CSVRecord();  
  53.         csvRecord.id = curruntRecord[0].trim();  
  54.         csvRecord.firstName = curruntRecord[1].trim();  
  55.         csvRecord.lastName = curruntRecord[2].trim();  
  56.         csvRecord.age = curruntRecord[3].trim();  
  57.         csvRecord.position = curruntRecord[4].trim();  
  58.         csvRecord.mobile = curruntRecord[5].trim();  
  59.         csvArr.push(csvRecord);  
  60.       }  
  61.     }  
  62.     return csvArr;  
  63.   }  
  64.   
  65.   isValidCSVFile(file: any) {  
  66.     return file.name.endsWith(".csv");  
  67.   }  
  68.   
  69.   getHeaderArray(csvRecordsArr: any) {  
  70.     let headers = (<string>csvRecordsArr[0]).split(',');  
  71.     let headerArray = [];  
  72.     for (let j = 0; j < headers.length; j++) {  
  73.       headerArray.push(headers[j]);  
  74.     }  
  75.     return headerArray;  
  76.   }  
  77.   
  78.   fileReset() {  
  79.     this.csvReader.nativeElement.value = "";  
  80.     this.records = [];  
  81.   }  
  82. }  
For a better look open "app.component.css",  copy the below css and paste it there.
 
  1. table.minimalistBlack {  
  2.     border3px solid #000;  
  3.     width100%;  
  4.     text-alignleft;  
  5.     border-collapsecollapse  
  6. }  
  7.   
  8. table.minimalistBlack td,  
  9. table.minimalistBlack th {  
  10.     border1px solid #000;  
  11.     padding5px 4px  
  12. }  
  13.   
  14. table.minimalistBlack tbody td {  
  15.     font-size13px  
  16. }  
  17.   
  18. table.minimalistBlack thead {  
  19.     background#cfcfcf;  
  20.     background: -moz-linear-gradient(top#dbdbdb 0#d3d3d3 66%, #cfcfcf 100%);  
  21.     background: -webkit-linear-gradient(top#dbdbdb 0#d3d3d3 66%, #cfcfcf 100%);  
  22.     background: linear-gradient(to bottom#dbdbdb 0#d3d3d3 66%, #cfcfcf 100%);  
  23.     border-bottom3px solid #000  
  24. }  
  25.   
  26. table.minimalistBlack thead th {  
  27.     font-size15px;  
  28.     font-weight700;  
  29.     color#000;  
  30.     text-alignleft  
  31. }  
  32.   
  33. table.minimalistBlack tfoot {  
  34.     font-size14px;  
  35.     font-weight700;  
  36.     color#000;  
  37.     border-top3px solid #000  
  38. }  
  39.   
  40. table.minimalistBlack tfoot td {  
  41.     font-size14px  
  42. }  
That’s it. Fire the following command to see the beauty!
  1. ng serve  
Open your browser on http://localhost:4200/ or click on “http://localhost:4200/”.
 

Output

 

Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.
 
You can download the source code from here.


Similar Articles