Angular 2上传解析CSV

时间:2018-06-27 19:51:23

标签: javascript angular api typescript opencsv

我是Angular的初学者,我正在尝试创建一种使用CSV文件上传和注册内容的功能。

如下:

parts.component.html

<div class="well">
  <form>
    <div class="row">
      <div class="col-md-10">
        <input class="form-control" id="file" name="file" (change)="readCsvData($event)" type="file" accept="text/plain">
      </div>
      <div class="col-md-2">
        <button class="btn btn-success" type="submit">Enviar arquivo</button>
      </div>
    </div>
  </form>
</div>

parts.component.ts

readCsvData(){
  let csvUrl = event.target;
  this.partService.upload(csvUrl)
}

part.service.ts

public upload(input: any){
    let url = this.partsUrl;
    let body = this.extractData(input);
    console.log(body);
    // return this.http.post()
  }
public extractData(data: any) {
    const file = data.files[0];
    const reader = new FileReader();
    reader.onload = function(e) {
      const content = reader.result;
      var lines = content.split("\n");
      var result = [];
      var headers = lines[0].split(",");
      for(var i = 1; i < lines.length; i++){
        var obj = {};
        var currentline = lines[i].split(",");
        for(var j = 0; j < headers.length; j++){
          obj[headers[j]] = currentline[j];
        }
        result.push(obj);
      }
      JSON.stringify(result);
    }
    reader.readAsText(file);
 }

但是我的Upload函数仅在变量主体中返回Undefined,而实际上它应该从extractData函数返回对象数组。

谢谢您!

2 个答案:

答案 0 :(得分:0)

尝试查看此npm软件包 csvtojson

如果您使用的是角度,则应使用const并让它,尽量不要使用var。

这就是我的用法

<input type="file" accept=".csv" (change)="convertFile($event)">

convertFile(event: any) {
  this.file = event.target.files[0];
  const reader = new FileReader();
  reader.readAsText(this.file);
  reader.onload = () => {
    this.textToCsv(reader.result);
  };
}

https://github.com/Robbie106gti/nc-catalog/blob/master/src/sop/components/csvtojson/csvtojson.component.ts

答案 1 :(得分:0)

类似于Rob的回答,但请勿将第三方程序包用于简单的字符串操作:

<input type="file" accept=".csv" (change)="processFile($event)">

processCsv(content){
    content.split('\n');
    // other sorts of magic
}

convertFile(event: any) {
  const file = event.target.files[0];
  readFileContent(file).then(content => {
    console.log('This is your file as string: ', content);
    // Operate your string as required in a separate function
    this.processCsv(content)    
  }).catch(error => console.log(error))
}

readFileContent(file) {
    const reader = new FileReader()
    return new Promise((resolve, reject) => {
    reader.onload = event => resolve(event.target.result)
    reader.onerror = error => reject(error)
    reader.readAsText(file)
  })
}