CSV file contains Comma separated values, records are distinguished by new line. By using split function we can get records easily.
Source Code        DEMO

Program Flow

  1. Get CSV file content using HTTP request
  2. Process CSV file data
  3. Format JavaScript object and display it in a table

Markup to display CSV content in Table

The below markup shows csvData in table view
<table border="1" class="demoTable">
   <tr *ngFor="let x of csvData">
      <td *ngFor="let y of x">{{ y }}</td>
   </tr>
</table>

Script - app.component.ts

Observe readCsvData and extractData functions. readCsvData functions sends GET request to server for CSV data, Once it got CSV data,  It will call extractData function, which will convert CSV data to two dimensional array.
import { Component } from '@angular/core';
import { Http, Response } from '@angular/http';

@Component({
  selector: 'my-app',
  template: `
  <h2>CSV Data</h2>
  <div>
    <button class="btn btn1 btn2" (click)="readCsvData()">
       Read CSV Data
    </button>
  </div>
  <br/><br/>
  <div>
    <table border="1" class="demoTable">
      <tr *ngFor="let x of csvData">
        <td *ngFor="let y of x">{{ y }}</td>
      </tr>
    </table>
  </div>
  `
})
export class AppComponent {
  csvUrl: string = 'sample.csv';  // URL to web API
  csvData: any[] = [];

  constructor (private http: Http) {}

  readCsvData () {
    this.http.get(this.csvUrl)
    .subscribe(
      data => this.extractData(data),
      err => this.handleError(err)
    );
  }

  private extractData(res: Response) {

    let csvData = res['_body'] || '';
    let allTextLines = csvData.split(/\r\n|\n/);
    let headers = allTextLines[0].split(',');
    let lines = [];

    for ( let i = 0; i < allTextLines.length; i++) {
        // split content based on comma
        let data = allTextLines[i].split(',');
        if (data.length == headers.length) {
            let tarr = [];
            for ( let j = 0; j < headers.length; j++) {
                tarr.push(data[j]);
            }
            lines.push(tarr);
        }
    }
    this.csvData = lines;
  }

  private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return errMsg;
  }
}

22 comments:

  1. With our url , I mean how to parse csv file browsed from our local system

    ReplyDelete
    Replies
    1. Did you get any replies? I'm looking for exact same thing.

      Delete
    2. I need to do same please reply if you get the solution.

      Delete
  2. can I convert the datas to json?

    ReplyDelete
  3. very easy to follow. thank you!

    ReplyDelete
  4. Have you had the following experience when combining a folder full of CSV files? Open a file, hit control A, hit control C, switch windows to the master file, find the point where you left off, hit control v, go back to the original file, close that file, select "no" when asked if you want to save the changes you made, locate the file in windows explorer, delete the file. excel reporting dashboard

    ReplyDelete
  5. I have csv file in which any cell can contain , eg("firstcellvalue", "second,cellvalue", "thirdcell,value").
    Using above code I am not able to get rid off.. Please help.

    ReplyDelete
  6. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete
  7. I want to upload the csv file runtime, do not want to set the csv URL.

    ReplyDelete


  8. Hats off to your presence of mind..I really enjoyed reading your blog. I really appreciate your information which you shared with us.
    Php course in chennai

    ReplyDelete
  9. It is not working for angular 5

    ReplyDelete
  10. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? english speaking lessons

    ReplyDelete
  11. Access to XMLHttpRequest at 'c:\fakepath\blood_data.csv' from origin 'http://localhost:4200' has been blocked by CORS policy:

    ReplyDelete
  12. Oleh karenanya keringanan dii dunia online begitu menolong anda bermain dengan aman serta memperoleh keuntungan.
    asikqq
    dewaqq
    sumoqq
    interqq
    pionpoker
    bandar ceme terpercaya
    hobiqq
    paito warna
    forum prediksi

    ReplyDelete
  13. Really informative article.Really looking forward to read more. Really Cool.
    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร Gclub กับทางทีมงานของเราเพียงเท่านั้น
    ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสล็อตออนไลน์ >>> goldenslot
    สนใจร่วมลงทุนกับเรา สมัครเอเย่น Gclub คลิ๊กได้เลย

    ReplyDelete
  14. Im grateful for the blog post.Really thank you!
    เว็บไซต์คาสิโนออนไลน์ที่ได้คุณภาพอับดับ 1 ของประเทศ
    เป็นเว็บไซต์การพนันออนไลน์ที่มีคนมา Gclub Royal1688
    และยังมีหวยให้คุณได้เล่น สมัครหวยออนไลน์ ได้เลย
    สมัครสล็อตออนไลน์ได้ที่นี่ >>> Golden slot
    ร่วมลงทุนสมัครเอเย่น Gclubกับทีมงานของเราได้เลย

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts