简体   繁体   English

从输入类型文件选择的CSV文件生成数组

[英]Generate array from CSV file selected by input type file

I want to read the CSV file that I upload using input type file and feed its data into an array. 我想读取使用输入类型文件上传的CSV文件,并将其数据输入数组。

I'm using Angularjs with input type file to read a CSV, xls or xlsx file as follows: 我正在将Angularjs与输入类型文件一起使用来读取CSV,xls或xlsx文件,如下所示:

HTML: HTML:

<input class="btn btn-default col-xs-6" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onchange="angular.element(this).scope().checkFormat(this.files)">

JavaScript/AngularJS: JavaScript / AngularJS:

$scope.checkFormat = function(files) {
        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);
}

How can I read this CSV file row by row and push each row into an array? 如何逐行读取此CSV文件并将每一行推入数组?

The best way it to make a directive with such functionality (say we call it csvUpload and use it like this <csv-upload ng-model="myData"> ) - this way it will be reusable and you won't have to implement this logic in, possibly, many controllers. 制作具有此类功能的指令的最佳方法(例如,我们称其为csvUpload并像这样<csv-upload ng-model="myData">一样使用它)-这种方式将可重用,而您无需实现这种逻辑可能存在于许多控制器中。 It's quite convenient too: once you have it you just choose a file and, bam, have your data on $scope.myData :) 这也很方便:一旦拥有它,您只需选择一个文件,然后将数据保存在$scope.myData :)

This is how I did it: 这是我的方法:

(To transform csv to json I'm using quite well estabilished https://github.com/mholt/PapaParse library but you could parse the csv string to json by yourself. I would not recommend it though ;) (要将csv转换为json,我使用的是已建立好的https://github.com/mholt/PapaParse库,但您可以自己将cv字符串解析为json。不过,我不建议这样做;)

.directive('csvUpload', function () {
  return {
    restrict: 'E',
    template: '<input type="file" onchange="angular.element(this).scope().handleFiles(this.files)">',
    require: 'ngModel',
    scope: {},
    link: function (scope, element, attrs, ngModel) {
      scope.handleFiles = function (files) {
        Papa.parse(files[0], {
          dynamicTyping: true,
          complete: function(results) {
            // you can transform the uploaded data here if necessary
            // ...
            ngModel.$setViewValue(results);
          }
        });
      };

    }
  };
});

** HTML ** HTML

** **

<input type="file" name="datasource_upload" accept="application/vnd.ms-excel, application/pdf,.csv" ngf-max-size="2MB" (change)="csv2Array($event)">

** **

Typescript code 打字稿代码

** **

    csv2Array(fileInput: any){
//read file from input
this.fileReaded = fileInput.target.files[0];

let reader: FileReader = new FileReader();
reader.readAsText(this.fileReaded);

reader.onload = (e) => {
  let csv: string = reader.result;
  let allTextLines = csv.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 
      console.log(tarr);
      lines.push(tarr);
    }
  }
  // all rows in the csv file 
  console.log(">>>>>>>>>>>>>>>>>", lines);
} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM