How to Read CSV File In Angular 7

Read CSV File In Angular

In this article, you’ll learn how to upload a CSV file from the UI rather than a static path or source, in order to make it dynamic.

Prerequisites

1] Basic knowledge of Angular 7
2] Visual Studio Code
3] Angular CLI must be installed
4] NodeJS must be installed

Let’s go to Visual Studio Code and open a new terminal.

Visual Studio Code

Type the following command and execute it in it.

ng new Angular7AppReadCSV

Go to the Root folder, select “Yes” for Angular routing, and use CSS for the stylesheet.

here, we create a new CSV file with the name of “CSVRecord” in the app folder and paste the below code.

export class CSVRecord {  
	public id: any;  
	public firstName: any;  
	public lastName: any;  
	public age: any;  
	public position: any;  
	public mobile: any;     
} 

Open the “app.component.html” file to and paste the below HTML code.

<input type="file" #csvReader name="Upload CSV" id="txtFileUpload" (change)="uploadListener($event)" accept=".csv" />    
<table class="minimalistBlack" *ngIf="records.length > 0">    
  <thead>    
    <tr>    
      <th>ID </th>    
      <th>FirstName </th>    
      <th>LastName </th>    
      <th>Age </th>    
      <th>Position </th>    
      <th>Mobile </th>    
    </tr>    
  </thead>    
  <tbody>    
    <tr *ngFor="let record of records;let i = index;">    
      <td> <span>{{record.id}}</span> </td>    
      <td> <span>{{record.firstName}}</span> </td>    
      <td> <span>{{record.lastName}}</span> </td>    
      <td> <span>{{record.age}}</span> </td>    
      <td> <span>{{record.position}}</span> </td>    
      <td> <span>{{record.mobile}}</span> </td>    
    </tr>    
  </tbody>    
</table>  

Let’s, open the “app.component.ts” file to write code which reads the CSV file and generates the file data in the table.

import { Component, ViewChild } from '@angular/core';  
import { CSVRecord } from './CSVModel';  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
  
export class AppComponent {  
  title = 'Angular7AppReadCSV';  
  
  public records: any[] = [];  
  @ViewChild('csvReader') csvReader: any;  
  
  uploadListener($event: any): void {  
  
    let text = [];  
    let files = $event.srcElement.files;  
  
    if (this.isValidCSVFile(files[0])) {  
  
      let input = $event.target;  
      let reader = new FileReader();  
      reader.readAsText(input.files[0]);  
  
      reader.onload = () => {  
        let csvData = reader.result;  
        let csvRecordsArray = (<string>csvData).split(/\r\n|\n/);  
  
        let headersRow = this.getHeaderArray(csvRecordsArray);  
  
        this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);  
      };  
  
      reader.onerror = function () {  
        console.log('error is occured while reading file!');  
      };  
  
    } else {  
      alert("Please import valid .csv file.");  
      this.fileReset();  
    }  
  }  
  
  getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {  
    let csvArr = [];  
  
    for (let i = 1; i < csvRecordsArray.length; i++) {  
      let curruntRecord = (<string>csvRecordsArray[i]).split(',');  
      if (curruntRecord.length == headerLength) {  
        let csvRecord: CSVRecord = new CSVRecord();  
        csvRecord.id = curruntRecord[0].trim();  
        csvRecord.firstName = curruntRecord[1].trim();  
        csvRecord.lastName = curruntRecord[2].trim();  
        csvRecord.age = curruntRecord[3].trim();  
        csvRecord.position = curruntRecord[4].trim();  
        csvRecord.mobile = curruntRecord[5].trim();  
        csvArr.push(csvRecord);  
      }  
    }  
    return csvArr;  
  }  
  
  isValidCSVFile(file: any) {  
    return file.name.endsWith(".csv");  
  }  
  
  getHeaderArray(csvRecordsArr: any) {  
    let headers = (<string>csvRecordsArr[0]).split(',');  
    let headerArray = [];  
    for (let j = 0; j < headers.length; j++) {  
      headerArray.push(headers[j]);  
    }  
    return headerArray;  
  }  
  
  fileReset() {  
    this.csvReader.nativeElement.value = "";  
    this.records = [];  
  }  
}   

Here, we add some CSS code For a better design, Let’s open the app.component.css, copy the below CSS and paste it there.

table.minimalistBlack {  
    border: 3px solid #000;  
    width: 100%;  
    text-align: left;  
    border-collapse: collapse  
}  
  
table.minimalistBlack td,  
table.minimalistBlack th {  
    border: 1px solid #000;  
    padding: 5px 4px  
}  
  
table.minimalistBlack tbody td {  
    font-size: 13px  
}  
  
table.minimalistBlack thead {  
    background: #cfcfcf;  
    background: -moz-linear-gradient(top, #dbdbdb 0, #d3d3d3 66%, #cfcfcf 100%);  
    background: -webkit-linear-gradient(top, #dbdbdb 0, #d3d3d3 66%, #cfcfcf 100%);  
    background: linear-gradient(to bottom, #dbdbdb 0, #d3d3d3 66%, #cfcfcf 100%);  
    border-bottom: 3px solid #000  
}  
  
table.minimalistBlack thead th {  
    font-size: 15px;  
    font-weight: 700;  
    color: #000;  
    text-align: left  
}  
  
table.minimalistBlack tfoot {  
    font-size: 14px;  
    font-weight: 700;  
    color: #000;  
    border-top: 3px solid #000  
}  
  
table.minimalistBlack tfoot td {  
    font-size: 14px  
}  

That’s it. Fire the following command to see the beauty!

ng serve

Open your browser on http://localhost:4200/ or click on “http://localhost:4200/”.

Read CSV File In Angular 7

Leave a Reply

Your email address will not be published. Required fields are marked *