Read CSV and convert JSON Data in Angular

In this article, we’ll learn how to read CSV files without any module. and that data display in the table also convert that data in JSON format to send data to the server. Let’s create a new project that you need to run following command


ng new csvread

“csvread” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go their directory. For example “cd csvread”. To Run angular applications, it required to run “ng serve”.
Let’s create a model “CsvData”. In CSV we have 4 fileds called id,min,max,score.


export class CsvData {
    public id: any;
    public min: any;
    public max: any;
    public score: any;
}



Let’s create “app.component.ts” in that we have create read CSV file function and conver json data function.


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 = (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();
    }
  }

Display below is the code for the app.component.ts ,app.component.html,app.component.css



/*
https://www.eduforbetterment.com/
*/
import { Component, VERSION ,ViewChild } from '@angular/core';


export class CsvData {
    public id: any;
    public min: any;
    public max: any;
    public score: any;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  public records: any[] = [];
  @ViewChild('csvReader') csvReader: any;
  jsondatadisplay: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 = (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 = (csvRecordsArray[i]).split(',');
      if (curruntRecord.length == headerLength) {
        let csvRecord: CsvData = new CsvData();
        csvRecord.id = curruntRecord[0].trim();
        csvRecord.min = curruntRecord[1].trim();
        csvRecord.max = curruntRecord[2].trim();
        csvRecord.score = curruntRecord[3].trim();
        csvArr.push(csvRecord);
      }
    }
    return csvArr;
  }

//check etension
  isValidCSVFile(file: any) {
    return file.name.endsWith(".csv");
  }

  getHeaderArray(csvRecordsArr: any) {
    let headers = (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 = [];
    this.jsondatadisplay = '';
  }

  getJsonData(){
    this.jsondatadisplay = JSON.stringify(this.records);
  }


}


<div class="container">
  
  <div class="card">
    <div class="card-header">
      Upload csv to read
    </div>
    <div class="card-body">

      <input type="file" #csvReader name="Upload CSV" id="txtFileUpload" (change)="uploadListener($event)" accept=".csv" />

    </div>
  </div>

<a href="javascript:;" *ngIf="records.length > 0" (click)="getJsonData()" class="btn btn-primary">Convert Json </a>

<a href="javascript:;" *ngIf="records.length > 0" (click)="fileReset()" class="btn btn-primary">Reset </a>  

{{jsondatadisplay}}
  <table class="table"  *ngIf="records.length > 0">
    <thead class="thead-dark" >
      <tr>
        <th scope="col">#</th>
        <th scope="col">Min</th>
        <th scope="col">Max</th>
        <th scope="col">Score</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let record of records;let i = index;">
        <th scope="row">{{record.id}}</th>
        <td>{{record.min}}</td>
        <td>{{record.max}}</td>
        <td>{{record.score}}</td>
      </tr>
  
    </tbody>
  </table>
</div>


p {
  font-family: Lato;
}
.table,.container{
  margin-top:20px; 
}
.btn{
  margin-right:20px; 
  margin-top: 20px;
}




Output

Below is the full embeded code for the read CSV. you can easily used in your application.
Example

Spread the love
  •  
  •  
  •  
  •  
  • 1
  • 2
  •  
  •