如何将数据表导出为角度的csv文件

时间:2016-12-13 05:45:00

标签: angularjs datatable

我在angularjs应用程序中有一个数据表,我想将它导出到csv文件.i在互联网上搜索了很多,我找到了这个指令,但这只有当按钮在桌子旁边时才有用。 需要帮助来编辑它......

app.directive('exportToCsv',function(){
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        var el = element[0];
        element.bind('click', function(e){
            var table = e.target.nextElementSibling;//need to access to this element directly
            var csvString = '';
            for(var i=0; i<table.rows.length;i++){
                var rowData = table.rows[i].cells;
                for(var j=0; j<rowData.length;j++){
                    csvString = csvString + rowData[j].innerHTML + ",";
                }
                csvString = csvString.substring(0,csvString.length - 1);
                csvString = csvString + "\n";
            }
            csvString = csvString.substring(0, csvString.length - 1);
            var a = $('<a/>', {
                style:'display:none',
                href:'data:application/octet-stream;base64,'+btoa(csvString),
                download:'emailStatistics.csv'
            }).appendTo('body')
            a[0].click()
            a.remove();
        });
    }
}
});

3 个答案:

答案 0 :(得分:3)

我建议您使用此网址http://www.w3schools.com/Bootstrap/bootstrap_ref_js_collapse.asp

上提供的UI网格

以下代码可让您导出为 PDF CSV

var app = angular.module('app', ['ngAnimate', 'ngTouch', 'ui.grid', 'ui.grid.selection', 'ui.grid.exporter', 'ui.grid.moveColumns']);

app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
  $scope.gridOptions = {
    columnDefs: [
      { field: 'name' },
      { field: 'gender', cellFilter: 'mapGender', exporterPdfAlign: 'right' },
      { field: 'company', visible: false }
    ],
    exporterLinkLabel: 'get your csv here',
    exporterPdfDefaultStyle: {fontSize: 9},
    exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
    exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red'},
    exporterPdfOrientation: 'portrait',
    exporterPdfPageSize: 'LETTER',
    exporterPdfMaxGridWidth: 500,
    exporterHeaderFilter: function( displayName ) { 
      if( displayName === 'Name' ) { 
        return 'Person Name'; 
      } else { 
        return displayName;
      } 
    },
    exporterFieldCallback: function( grid, row, col, input ) {
      if( col.name == 'gender' ){
        switch( input ){
          case 1:
            return 'female';
            break;
          case 2:
            return 'male';
            break;
          default:
            return 'unknown';
            break;
        }
      } else {
        return input;
      }
    },
    onRegisterApi: function(gridApi){ 
      $scope.gridApi = gridApi;
    }
  };

  $http.get('/data/100.json')
    .success(function(data) {
      data.forEach( function( row, index ) {
        if( row.gender === 'female' ){
          row.gender = 1;
        } else {
          row.gender = 2;
        }
      });
      $scope.gridOptions.data = data;
    });



  $scope.export = function(){
    if ($scope.export_format == 'csv') {
      var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
      $scope.gridApi.exporter.csvExport( $scope.export_row_type, $scope.export_column_type, myElement );
    } else if ($scope.export_format == 'pdf') {
      $scope.gridApi.exporter.pdfExport( $scope.export_row_type, $scope.export_column_type );
    };
  };
}])

.filter('mapGender', function() {
  return function( input ) {
    switch( input ){
      case 1:
        return 'female';
        break;
      case 2:
        return 'male';
        break;
      default:
        return 'unknown';
        break;
    }
  };
});

HTML看起来像

  <div ui-grid="gridOptions" ui-grid-selection ui-grid-exporter ui-grid-move-columns class="grid"></div>

答案 1 :(得分:2)

你可以做到这一点

<div *ngIf="pages"> 
  <h4 class="block-title">{{ pages.Title }}</h4>

  <div class="about-project">
    <p>{{ pages.Content }}</p>
  </div>
</div>

你必须将nextElementSibling更改为previousElementSibling

答案 2 :(得分:1)

getElementById()用于动态元素访问

<强>指令

app.directive('exportToCsv',function(){ return { restrict: 'A', link: function (scope, element, attrs) { var el = element[0]; element.bind('click', function (e) { var idName = e.target.name; var fileName = idName.split("--")[0]; var tableId = idName.split("--")[1]; var table = document.getElementById(tableId); var csvString = ''; for (var i = 0; i < table.rows.length; i++) { var rowData = table.rows[i].cells; for (var j = 0; j < rowData.length; j++) { csvString = csvString + rowData[j].innerHTML + ","; } csvString = csvString.substring(0, csvString.length - 1); csvString = csvString + "\n"; } csvString = csvString.substring(0, csvString.length - 1); var a = $('<a/>', { style: 'display:none', href: 'data:application/octet-stream;base64,' + btoa(csvString), download: fileName + '.csv' }).appendTo('body') a[0].click() a.remove(); }); } } });

<强> HTML

<button type="button" class="btn btn-primary" name="filename--divId" export-to-csv>Export posts</button>

在按钮标记中添加名称元素,第一部分是文件名&amp;第二部分是要选择的div的id。

谢谢。