How To Read CSV File In Angular

How To Read CSV File In Angular

In angular several CSV, reader libraries are available, however, In this article, we will learn about how to read a CSV file without using any libraries and upload a CSV file from the UI rather than a static path or source, making it dynamic.

So, let's start with the implementation

First, we need to create a new angular application using the following command in the terminal.

ng new Angular-CSVread

Now, we need to create a new file called CSVRecord.ts and add the following code to it.

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

Now, add the following code under the app.component.html file.

<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, using the following code add core logic under the app.component.ts file which reads a CSV file and generates file data for a 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 = [];
  }
}

Now, using the following code add some table style into the app.component.css file for good looking design.

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
}

Now run the application using the ng serve command into the terminal and see the browser screen. Now we are able to browse CSV files and read all the data and display it in the table.

Conclusion

In this article, we learn how to read a CSV file without using any libraries and display it in table format in an angular application.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post