3

I'm working with Angular 6 , I'm new in it, trying more then 8 hours to read a csv file I have locally, and fill an array from the information is written at the csv. the csv have Values separated by a comma, Rows are separated by a new-line. can anyone help me please, I'm stacked...

here is The TeacherModel.ts

export class TeacherModel {
    id:number;
    name: string;
    lastName: string;
    nikName: string;
    id1: string;
    Sunday:number;
    Monday :number;
    Tuesday :number;
    Wednesday:number; 
    Thursday :number;
    Friday :number;

    Sunday1:number;
    Monday1 :number;
    Tuesday1 :number;
    Wednesday1:number; 
    Thursday1 :number;
    Friday1 :number;

}

3
  • You could use Papa Parse wrapper for Angular (see npmjs.com/package/ngx-papaparse) Commented Nov 4, 2019 at 11:11
  • @אסתר trying to read file that you uploaded or in the assets folder ? Commented Nov 4, 2019 at 12:01
  • in the assets folder Commented Nov 6, 2019 at 7:29

3 Answers 3

1

You can try Papa Parser:

npm install ngx-papaparse@4 --save

Example:

const resultFile = httpClient.get('/assets/test-data.csv', {responseType: 'text'}).subscribe(file => {
      file.split(/[\r\n]+/).forEach(line => {
        this.papa.parse(line, {
          complete: (result) => {
            console.log('Parsed: ', result);
          }
        });
      });
    });

Considering your file is placed inside assets directory. I just print the array on console, you can do whatever you want.

Sign up to request clarification or add additional context in comments.

5 Comments

thank you for your answer, where do i need to declare httpclient, and papa, he doesn't recognize me them
ngOnInit () { const resultFile = this.httpClient.get('./data/teachers.csv', {responseType: 'text'}).subscribe(file => { file.split(/[\r\n]+/).forEach((line , i) => {i++; this.papa.parse(line, { complete: (result) => { this.teachersList[i].id=result[i]; this.teachersList[i].id1=result[i]; this.teachersList[i].name=result[i]; this.teachersList[i].lastName=result[i];*********** why it's not working... :(
You need to inject it into constructor like constructor(private papa: Papa, httpClient: HttpClient) { const resultFile = httpClient.get('/assets/test-data.csv', {responseType: 'text'}).subscribe(file => { file.split(/[\r\n]+/).forEach(line => { this.papa.parse(line, { complete: (result) => { console.log('Parsed: ', result); } }); }); }); }
and make sure you have imported HttpClientModule in your app.module.ts file
I did it exacly like you wrote, it's not working :( he doesn't find the path "Http failure response for localhost:4200/data/teachers.json: 404 Not Found"
0

Use this way put your csv file in assets folder

import { HttpClient } from "@angular/common/http";

export class AppComponent  {
  public userArray: User[] = [];
  constructor(private http: HttpClient){
    this.http.get('assets/csv.csv', {responseType: 'text'})
    .subscribe(
        data => {
            let csvToRowArray = data.split("\n");
            for (let index = 1; index < csvToRowArray.length; index++) {
              let row = csvToRowArray[index].split(",");
              this.userArray.push(new User( parseInt( row[0], 10), row[1], row[2].trim()));
            }
            console.log(this.userArray);
        },
        error => {
            console.log(error);
        }
    );
  }
}

export class User{
  id: number;
  name: String;
  lastName: String;

  constructor(id: number, name: String, lastName: String){
    this.id = id;
    this.name = name;
    this.lastName = lastName;
  }
}

Stackblitz example

Comments

0

PapaParse is good CSV parser for Javascript, and it will help you to read CSV from local or remote path, but again you need to construct it to your class and you need again one more package like https://www.npmjs.com/package/class-transformer , unless you want to write your own personal implementation for transforming json response to modal class.

Now, the question is how big your CSV is and do you really want to use these above mentioned libraries, if you just want to transform local CSV from HTTPGET to class than alone class-transformer is good enough, but if you want multiple operation on big heavy csv file then use papa parse as well, please refer https://www.papaparse.com/docs#config for all option provided by papa parse.

Please find below my personal implementation of papa parse and csv transformer both the libraries.

 import * as jsonParse from 'papaparse';
 import { plainToClass } from 'class-transformer';

 fetchDataFromCSV() {
     return this.httpClient.get(this.csvPath, { responseType: 'text' })
     .toPromise()
     .then(res => this.getPersons(res));
  }

 getPersons(res): Person[] {

     const csvData = res;
     const parsedData = jsonParse.parse(csvData, this.parseConfig).data;

      // parseConfig is papa parse option object, refer https://www.papaparse.com/docs#config for all posible parsing options.

     this.headerRow = parsedData[0]; // if you want to do something with header row
     const allPersons = plainToClass(Person, parsedData as Object[]);
     return allPersons;
 }

1 Comment

It´s help me a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.