Reputation: 8971
I want to read the CSV file that I upload using input type file and feed its data into an array.
I'm using Angularjs with input type file to read a CSV, xls or xlsx file as follows:
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]);
}
How can I read this CSV file row by row and push each row into an array?
Upvotes: 0
Views: 1828
Reputation: 677
** 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);
} }
Upvotes: 0
Reputation: 7201
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. It's quite convenient too: once you have it you just choose a file and, bam, have your data on $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 ;)
.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);
}
});
};
}
};
});
Upvotes: 2