npm i papaparse
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HelloComponent } from './hello.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } |
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { Component, OnInit } from '@angular/core'; import * as Papa from 'papaparse'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { name = 'Angular CSV File Parser Example'; dataList: any[] = []; headers: string[] = []; // To store the dynamic column headers ngOnInit() {} onChange(files: File[]) { if (files[0]) { Papa.parse(files[0], { header: true, // Automatically detect headers skipEmptyLines: true, complete: (result) => { console.log(result); this.dataList = result.data; this.headers = result.meta.fields || []; // Get headers from metadata } }); } } } |
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<input type="file" name="files" class="form-control" #uploads (change)="onChange(uploads.files)" multiple value="process" /> <div> <table border=""> <thead> <tr> <th *ngFor="let header of headers">{{ header }}</th> </tr> </thead> <tbody> <tr *ngFor="let record of dataList"> <td *ngFor="let header of headers">{{ record[header] }}</td> </tr> </tbody> </table> </div> |
FULL SOURCE CODE