Angular 4 - 上传CSV

fan*_*gio 3 html csv json typescript angular

我正在制作一个Angular4我有一个按钮,可以将数据转换为带有标题的csv文件.现在我想反过来做,我想上传一个csv文件.因此,为了进行测试,我创建了一个对象并从中创建了一个csv文件,然后我想单击一个按钮并上传该文件并获得相同的结果.

我找到了一个导出csv的角度模块,但我找不到一个相反的方法.有人可以帮助我吗?

这是我的代码:

test.ts

import { Component, OnInit} from '@angular/core';
import { Angular2Csv } from 'angular2-csv/Angular2-csv';
import {Unit} from "../../../_shared/unit";

@Component({
  moduleId: module.id,
  templateUrl: 'test.component.html',
  styleUrls: ['./test.css']
})


export class TestComponent implements OnInit {



  ngOnInit() {}

  public export() {
    // Unit (id,name,description)
    var data = [new Unit(1,"Unit1","This is unit 1!")];

    var options = {
      fieldSeparator: ';',
      quoteStrings: '"',
      decimalseparator: ',',
      showLabels: true,
      useBom: true
    };
    new Angular2Csv(data, "data", options);
  }

  public import(){}

}
Run Code Online (Sandbox Code Playgroud)

的test.html

<button (click)="export()">Download CSV</button>
<button (click)="import()">Upload CSV</button>
Run Code Online (Sandbox Code Playgroud)

Fah*_*sar 7

您可以使用自定义函数实现该功能,试试这个:

private extractData(data) { // Input csv data to the function

    let csvData = data;
    let allTextLines = csvData.split(/\r\n|\n/);
    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]);
            }
            lines.push(tarr);
        }
    }
    console.log(lines); //The data in the form of 2 dimensional array.
  }
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到详细的帖子:http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html#.WWxu9XV97OQ

您可以像这样读取文件侦听器函数中的文件:

function handleFileSelect(evt) {
      var files = evt.target.files; // FileList object
      var file = files[0];
      var reader = new FileReader();
      reader.readAsText(file);
      reader.onload = function(event){
        var csv = event.target.result; // Content of CSV file
        this.extractData(csv); //Here you can call the above function.
      }

}
Run Code Online (Sandbox Code Playgroud)

在html里面这样做:

 <input type="file" (change)="handleFileSelect($event)"/>
Run Code Online (Sandbox Code Playgroud)

  • 它与angular 4和新的打字稿有关,我必须定义一个新的界面才能使它工作,https://github.com/Microsoft/TypeScript/issues/299#issuecomment-168538829 (2认同)