Read CSV File In Angular 7

Introduction

There are lots of CSV reader libraries available for Angular 7 but We will read CSV file 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.
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.

code .

Create one new file namely “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>

Now, open the “app.component.ts” file to write our main logic which read CSV file and generate 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 = 'Angular7-readCSV';

  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 = [];
  }
}

for some better looks open “app.component.css” copy below css and paste 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/”.
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.

 

1 Comment

  1. hamza hasnaoui

    how can i send content of csv file to server spring bootapi rest

    0
    0
    Reply

Submit a Comment

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

Subscribe

Select Categories