如何上传CSV文件并使用angular2阅读?

时间:2017-08-01 15:31:29

标签: angular

我需要上传一个.CSV文件并在我的组件中读取它们,我已经浏览了这个博客但它有一个.CSV文件存储在一个特定的loaction中,我想上传.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文件的内容,有人可以帮我吗?

谢谢

4 个答案:

答案 0 :(得分:15)

将您的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);
       }
    }
}

答案 1 :(得分:2)

我在我的应用上制作了上传功能。希望它有所帮助

这是我的组件

中的示例上传功能
class Program
{
    static void Main(string[] args)
    {
        var props = typeof(Foo).GetProperties();
        var filtered = props
            .Where(x => x.GetCustomAttributes(typeof(FirstAttribute), false).Length > 0)
            .ToList();
        var propertyDescriptor = TypeDescriptor.GetProperties(typeof(Foo))
            .Find(filtered[0].Name, false);
    }
}
class Foo
{
    [First]
    public string SomeString { get; set; }

    [First(SomeFlag = true)]
    public int SomeInt { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
class FirstAttribute : Attribute
{
    public bool SomeFlag { get; set; }
}

这是我的服务类

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

}

这是我的HTML

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))

  }
}

答案 2 :(得分:1)

将您的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;
  }
}

答案 3 :(得分:0)

针对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/