简体   繁体   中英

How to read a csv file in angularjs

I am trying to read a csv file in angular js and i got through this question How to read csv file content in angular js? where it is used as directive.But i am submitting it as a form in my controler ,so how can i use in my form.Can anyone suggest help.Thanks.

My code,

  if($scope.partner.csv){
          var files = $scope.partner.csv.target.files
           var r = new FileReader();
           r.onload = function(e) {
               var contents = e.target.result;
                $scope.$apply(function () {
                 $scope.fileReader = contents;
               });
          };
        }
      }

This is what i had tried,when i submit my form if csv file is uploaded the above action should be done.

You can use the below code to read csv file.

<!DOCTYPE html>
<html ng-app="" ng-controller="myCtrl">
<style>
table, th, td {
   border: 1px solid black;
   padding:5px;
}
table {
   border-collapse: collapse;
   margin:10px;
}
</style>
<body>
<button ng-click="readCSV()">
Display CSV as Data Table
</button>
<div id="divID">
  <table>
    <tr ng-repeat="x in data">
      <td ng-repeat="y in x">{{ y }}</td>
    </tr>
  </table>
</div>
<div>
<table>
</table>
</div>
<script>
function myCtrl($scope, $http) {
    $scope.readCSV = function() {
        // http get request to read CSV file content
        $http.get('/angular/sample.csv').success($scope.processData);
    };

    $scope.processData = function(allText) {
        // split content based on new line
        var allTextLines = allText.split(/\r\n|\n/);
        var headers = allTextLines[0].split(',');
        var lines = [];

        for ( var i = 0; i < allTextLines.length; i++) {
            // split content based on comma
            var data = allTextLines[i].split(',');
            if (data.length == headers.length) {
                var tarr = [];
                for ( var j = 0; j < headers.length; j++) {
                    tarr.push(data[j]);
                }
                lines.push(tarr);
            }
        }
        $scope.data = lines;
    };
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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