How to upload a CSV file and read them using angular2?

前端 未结 4 1020
野趣味
野趣味 2020-12-15 05:49

i have a requirement of uploading a .CSV file and read them inside my component, i have gone through this blog but it has a .CSV file stored in a particular loaction, i want

4条回答
  •  离开以前
    2020-12-15 06:28

    upload your csv file to a location and get the location URL and the uploaded csv file name and use this service i created.

    import { Injectable, Inject} from '@angular/core';
    import { Http } from '@angular/http';
    import {HttpService} from './http.service';
    @Injectable()
    export class CSVSERVICE {
      csvUrl: string = './csv_upload?id=';  // URL to web API
      csvData: any[] = [];
    
      constructor (private http: Http) {}
    
      readCsvData (fileName) {
       return  this.http.get(this.csvUrl + fileName)
        .map(
          (idata) => {
            let csvData = idata['_body'] || '';
        let allTextLines = csvData.split(/\r?\n|\r/);
        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]);
                } 
    
    // log each row to see output and 
                console.log(tarr);
                lines.push(tarr);
            }
        }
        return lines;
          }, // this.extractData,
          err => this.handleError(err)
        );
      }
    
    
    
      private handleError (error: any) {
        let errMsg = (error.message) ? error.message :
          error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return errMsg;
      }
    }
    

提交回复
热议问题