如何将CSV文件中的数据读取到TypeScript中的数组中,然后从中随机选择一个项目

时间:2019-02-10 14:56:45

标签: typescript csvtoarray

我正在尝试编写一个程序,该程序可以从名称列表中随机选择一个学生的姓名。名称列表应使用CSV文件格式添加,并将这些名称放入数组中,这样,如果学生不在课上,则可以“屏蔽”该学生的姓名,这样就不会选择他们的姓名。

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Http } from '@angular/http';
import * as papa from 'papaparse';

@IonicPage()
@Component({
  selector: 'page-csv',
  templateUrl: 'csv.html',
})
export class CsvPage {
  csvData: any[] = [];
  headerRow: any[] = [];

constructor(
    public navCtrl: NavController, 
    public navParams: NavParams, 
    private http: Http) {
    // this.readCsvData();
  }
/* 
  private readCsvData() {
    this.http.get('assets/csv.csv')
      .subscribe(
      data => this.extractData(data),
      err => this.handleError(err)
      );
  }

  private extractData(res) {
    let csvData = res['_body'] || '';
    let parsedData = papa.parse(csvData).data;

    this.headerRow = parsedData[0];

    parsedData.splice(0, 1);
    this.csvData = parsedData;
  }

   downloadCSV() {
    let csv = papa.unparse({
      fields: this.headerRow,
      data: this.csvData
    });

    var blob = new Blob([csv]);
    var a = window.document.createElement("a");
    a.href = window.URL.createObjectURL(blob);
    a.download = "newdata.csv";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  private handleError(err) {
    console.log('An error has occured: ', err);
  }

  trackByFn(index: any, item: any) {
    return index;
  }
} 

handleFiles(files) {
  // Check for the various File API support.
  if (window.FileReader) {
      // FileReader are supported.
  } else {
      alert('FileReader are not supported in this browser.');
  }
}
*/
getAsText(fileToRead) {
  var reader = new FileReader();     
  reader.readAsText(fileToRead)
  reader.onload = this.loadHandler;
  reader.onerror = this.errorHandler;
}

loadHandler(event) {
  var csv = event.target.result;
  this.processData(csv);
}

processData(csv) {
    var allTextLines = csv.split(/\r\n|\n/);
    var lines = [];
    for (var i=0; i<allTextLines.length; i++) {
        var data = allTextLines[i].split(';');
            var tarr = [];
            for (var j=0; j<data.length; j++) {
                tarr.push(data[j]);
            }
            lines.push(tarr);
    }
  console.log(lines);
}

errorHandler(evt) {
  if(evt.target.error.name == "NotReadableError") {
      alert("Canno't read file !");
  }
}
}

/ *和* /之间的代码是我尝试执行的第一种方法,但是没有用。

它应该输出可以在应用程序内修改的名称列表。我该怎么办?

0 个答案:

没有答案