繁体   English   中英

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

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

我想读取使用输入类型文件上传的CSV文件,并将其数据输入数组。

我正在将Angularjs与输入类型文件一起使用来读取CSV,xls或xlsx文件,如下所示:

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:

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

如何逐行读取此CSV文件并将每一行推入数组?

制作具有此类功能的指令的最佳方法(例如,我们称其为csvUpload并像这样<csv-upload ng-model="myData">一样使用它)-这种方式将可重用,而您无需实现这种逻辑可能存在于许多控制器中。 这也很方便:一旦拥有它,您只需选择一个文件,然后将数据保存在$scope.myData :)

这是我的方法:

(要将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

**

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

**

打字稿代码

**

    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