我想读取使用输入类型文件上传的 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">
) - 这样它将可以重用,并且您不会必须在可能的许多 Controller 中实现此逻辑。它也很方便:一旦你有了它,你只需选择一个文件,然后,bam,你的数据就在 $scope.myData
上。 :)
我就是这样做的:
(为了将 csv 转换为 json,我使用了相当完善的 https://github.com/mholt/PapaParse 库,但您可以自己将 csv 字符串解析为 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);
}
});
};
}
};
});
关于javascript - 从输入类型文件选择的 CSV 文件生成数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31047907/