31
27

More than 5 years have passed since last update.

angular-PapaParseを使ってcsvをパース(解析)する

Last updated at Posted at 2015-10-20

はじめに

csvファイルを読み込んで、json形式にパースするまでを行う。

前提

angularJSを使用します。

使用するライブラリは下記になります。

◎csvパース用
angular-PapaParse
angular-PapaParseはPapa Parseをangularでラップしたものになります。
その為、使い方はPapa Parseのサイトを見ると詳しくわかります。

◎csvファイル読み込み用
ng-file-upload
ファイルを取得する為に使用しています。このライブラリである必要は特に無いです。

※ng-file-uploadの使い方の説明は省きます。

使い方

◎ローカルのcsvファイルをjson形式にパースします。

Papa.parse関数の引数として、fileオブジェクトを渡します。

 <button ngf-select ng-model="files" ngf-change="parseFile(files)">csvファイル選択<button>
angular.module('App', [])
  .controller(AppCtrl, ['$scope', function($scope) {

    $scope.parseFile = function(files) {
      Papa.parse(files[0], {
        complete: function(results) {
        },
        error:function(){
        }
      })
    }

  }]);

◎サーバー上のcsvファイルをjson形式にパースします。

Papa.parse関数の引数として、fileパスを渡します。
プロパティとしてdownloadを追加します。

 <button ng-click="parseFile('http://www.hogehoge/sample.csv')">csvをパース<button>
angular.module('App', [])
  .controller(AppCtrl, ['$scope', function($scope) {

    $scope.parseFile = function(url) {
      Papa.parse(url, {
        download:true,
        complete: function(results) {
        }
      })
    }

  }]);

◎大きいデータを扱う場合

stepプロパティを使用することで、ストリーミングでデータを取得することができます。
stepの引数にはcsvの1行ごとに結果が返却されます。

 <button ng-click="parseFile('http://www.hogehoge/sample.csv')">csvをパース<button>
angular.module('App', [])
  .controller(AppCtrl, ['$scope', function($scope) {

    $scope.parseFile = function(url) {
      Papa.parse(url, {
        step: function(row) {
          console.log(row.data);
        },
        download:true,
        complete: function(results) {
        }
      })
    }

  }]);

◎ファイルのエンコードを指定する

下記条件でcsvをパースした場合文字化けをした。
・csvがShift-JISで作成されている
・jsがUTF-8で記載されている

encodingプロパティを追加して'Shift-JIS'を指定したら文字化けが解消した。

 <button ngf-select ng-model="files" ngf-change="parseFile(files)">csvファイル選択<button>
angular.module('App', [])
  .controller(AppCtrl, ['$scope', function($scope) {

    $scope.parseFile = function(files) {
      Papa.parse(files[0], {
        encoding: 'Shift-JIS',
        complete: function(results) {
        },
        error:function(){
        }
      })
    }

  }]);

◎ヘッダーの制御

csvの1行目が各カラムのタイトルとなっている場合に
headerプロパティを使用します。

"header1","header2","header3","header4","header5"
"A","B","C","D","E"
 <button ngf-select ng-model="files" ngf-change="parseFile(files)">csvファイル選択<button>
angular.module('App', [])
  .controller(AppCtrl, ['$scope', function($scope) {

    $scope.parseFile = function(files) {
      Papa.parse(files[0], {
        header: true,
        complete: function(results) {
           console.log(results.data)
        },
        error:function(){
        }
      })
    }

  }]);
結果

//header:true
        data: {
          [
            header1: "A"
            header2: "B"
            header3: "C"
            header4: "D"
            header5: "E"
          ]
        }

//header:false
      data: {
        [
          0: "header1"
          1: "header2"
          2: "header3"
          3: "header4"
          4: "header5"
        ], [
          0: "A"
          1: "B"
          2: "C"
          3: "D"
          4: "E"
        ]
      }

◎データを数字として取得する

データ内の数値(String型)をNumber型として取得したい場合に、
dynamicTypingプロパティを使用する。

"1.234","200","+3","-4","05"
 <button ngf-select ng-model="files" ngf-change="parseFile(files)">csvファイル選択<button>
angular.module('App', [])
  .controller(AppCtrl, ['$scope', function($scope) {

    $scope.parseFile = function(files) {
      Papa.parse(files[0], {
        dynamicTyping: true,
        complete: function(results) {
           console.log(results.data)
        },
        error:function(){
        }
      })
    }

  }]);
結果

//dynamicTyping:true
      data: {
        [
          0: 1.234
          1: 200
          2: "+3"
          3: -4
          4: 5
        ]
      }
//dynamicTyping:false
      data: {
        [
          header1: "1.234"
          header2: "200"
          header3: "+3"
          header4: "-4"
          header5: "05"
        ]
      }

記載した内容以外にも便利な機能があるようなので、詳しくはPapaParseのドキュメントページを見てみてください。

31
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
27