【问题标题】:How to upload a CSV file and read them using angular2?如何上传 CSV 文件并使用 angular2 读取它们?
【发布时间】:2017-08-01 15:31:29
【问题描述】:

我需要上传 .CSV 文件并在我的组件中读取它们,我已经浏览了这个博客,但它有一个 .CSV 文件存储在特定位置,我想上传 .CSV 文件并阅读它们在我的组件内。我该怎么做呢

我们有可以使用的内置插件吗?如果没有,那么我们如何才能实现这个目标。

这是我尝试过的代码

查看

<input type="file" name="File Upload" id="txtFileUpload" 
        (change)="changeListener($event)" 
        accept=".csv"/>

组件

changeListener($event:Response): void {
    debugger;
   // i am not able to get the data in the CSV file
  }

在 changeListener() 中,我无法获取 .CSV 文件的内容,谁能帮我解决这个问题?

谢谢

【问题讨论】:

标签: angular


【解决方案1】:

将您的 csv 文件上传到某个位置并获取 csv 文件数据。请试试这个:-

Component.html:-

<input type="file" class="upload" (change)="changeListener($event.target.files)">

Component.ts:-

public changeListener(files: FileList){
  console.log(files);
  if(files && files.length > 0) {
     let file : File = files.item(0); 
       console.log(file.name);
       console.log(file.size);
       console.log(file.type);
       let reader: FileReader = new FileReader();
       reader.readAsText(file);
       reader.onload = (e) => {
          let csv: string = reader.result as string;
          console.log(csv);
       }
    }
}

【讨论】:

  • @Harleen,它抛出错误 ** [ts] 类型 'string | ArrayBuffer' 不可分配给类型 'string'。类型“ArrayBuffer”不可分配给类型“字符串”。**
  • @Anjali: 附加as string 所以该行显示为let csv: string = reader.result as string;
【解决方案2】:

我在我的应用上做了一个上传功能。希望对你有帮助

这是我的组件内的示例上传功能

uploadDatasource(fileInput: any) {

let file = fileInput.target.files[0];
let fileName = file.name;


let payload = {
  file,
}

let formData: FormData = new FormData();
formData.append('file',file,file.name);


this.DsListService.uploadDatasource(formData)
  .subscribe(
    response => { 
      console.log('UPLOADING success');


    },
    error => {
      console.log('error',error)
    });

}

这是我的服务类

import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Config } from '../config/config';

@Injectable()
export class DsListService {

  private config = new Config;

  constructor(private http: Http) { }


  uploadDatasource(payload): Observable<any[]> {
    let headers = new Headers();

    headers.append('Accept', 'application/json, text/plain,');
    let options = new RequestOptions({ headers: headers });


    return this.http.post(`API_UPLOAD_PATH`,payload, options)
      .map((res: Response) => {
        let data = res.json();
        return data;
      })
      .catch(error => Observable.throw(error))

  }
}

这是我的html

<input type="file" [(ngModel)]="Model.datasourcelistdata" name="datasource_upload" id="datasource_upload" accept=".xlsx,.xls,.csv" ngf-max-size="20MB" fd-input (change)="uploadDatasource($event)" />

【讨论】:

  • 我不想将它上传到文件位置,我想在 angular2 本身中处理上传的 .CSV 文件。我该怎么做?任何想法
  • 您无法使用 Angular2 操作上传的数据/csv,因为前端的东西无法处理文件系统。您需要在您的服务器上构建您的逻辑,例如nodejs,php,python 等。
【解决方案3】:

将您的 csv 文件上传到某个位置并获取位置 URL 和上传的 csv 文件名并使用我创建的此服务。

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;
  }
}

【讨论】:

    【解决方案4】:

    Angular 的 Papa Parse 包装库是在 Angular 组件中解析 CSV 文件的最佳解决方案之一。您可以使用以下命令为 Angular 6 和 7 安装该库:

    npm install ngx-papaparse@3 --save
    

    首先将 PapaParseModule 导入您的应用。

    import { PapaParseModule } from 'ngx-papaparse';
    
    @NgModule({
      ...
      imports: [
        ...
        PapaParseModule
      ]
    })
    

    在您的组件模板中:

    <input type="file" #fileImportInput name="CSV File Upload" 
    (change)="fileChangeListener($event)" accept=".csv">
    

    然后在组件或服务中使用它:

    import { Component } from '@angular/core';
    import { Papa } from 'ngx-papaparse';
    
    @Component({
      ...
    })
    export class AppComponent {
    
        constructor(private papa: Papa) {
    
            // TEST IF YOUR PARSER IS WORKING FINE
            const csvData = '"Hello","World!"';
    
            this.papa.parse(csvData,{
                complete: (result) => {
                    console.log('Parsed: ', result);
                }
            });
        }
    
      // LOAD CSV FILE FROM INPUT
      fileChangeListener($event: any): void {
    
        const files = $event.srcElement.files;
    
        if (files !== null && files !== undefined && files.length > 0) {
          this.selectedCSVFileName = files[0].name;
    
          const reader: FileReader = new FileReader();
          reader.readAsText(files[0]);
          reader.onload = e => {
    
            const csv = reader.result;
            const results = this.papa.parse(csv as string, { header: false });
    
            // VALIDATE PARSED CSV FILE
            if (results !== null && results !== undefined && results.data !== null &&
              results.data !== undefined && results.data.length > 0 && results.errors.length === 0) {
              this.isCSV_Valid = true;
    
              // PERFORM OPERATIONS ON PARSED CSV
              let csvTableHeader = results.data[0];
    
              let csvTableData = [...results.data.slice(1, results.data.length)];
    
            } else {
              for (let i = 0; i < results.errors.length; i++) {
                console.log( 'Error Parsing CSV File: ',results.errors[i].message);
              }
            }
          };
        } else {
          console.log('No File Selected');
        }
    
      }
    }
    

    *注意:如果您不想使用库并手动解析 CSV 文件,您也可以这样做。

    以下是解析 CSV 文件的参考博文:https://blog.developershive.com/how-to-import-csv-file-in-angular-7-no-library-needed/blog/develkwl/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-23
      • 2018-03-26
      • 2015-06-26
      • 1970-01-01
      • 2018-12-14
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多