生成的Excel为空

时间:2018-03-26 16:58:30

标签: javascript html angularjs

我从后端获取数据并使用angularjs将其导出到excel。当我点击导出按钮时,它正在下载一个空白的Excel工作表而不是我的数据。

我无法追踪问题,我尝试使用$timeout,但excel仍然生成空白而没有数据。有什么输入吗?

修改

当有后端呼叫时,它不会等到响应从后端返回并生成空白文件,我尝试使用$timeout功能但是没有工作。

代码:

myApp.controller('modalCtrlTest', function ($scope, UserService) {
    $scope.dataToExport = function(){
      $scope.allDataInfomation();

    }
    $scope.allDataInfomation = function(){

/*  $scope.jsonToExport = [
    {
        "col1data": "1",
      "col2data": "Fight Club",
      "col3data": "Brad Pitt"
    },
    {
        "col1data": "2",
      "col2data": "Matrix (Series)",
      "col3data": "Keanu Reeves"
    },
    {
        "col1data": "3", 
      "col2data": "V for Vendetta",
      "col3data": "Hugo Weaving"
    }
  ];*/

  //service call to get the data from backend
  UserService.getDataFromBackEnd().then(
    function(response){
      $scope.jsonToExport = response;
    });
    $scope.fileName = "report";
    $scope.exportData.push(["#", "Movie", "Actor"]);
  // Data 
    angular.forEach($scope.jsonToExport, function(value, key) {
    $scope.exportData.push([value.mID, value.mName, value.mActor]);
    });
  }

    //export button directive code
    $scope.exportData = [];
  var fileName
    $scope.download = function() {  //This method is called when clicked on the Export  button
        $scope.dataToExport();
        function datenum(v, date1904) {
            if(date1904) v+=1462;
            var epoch = Date.parse(v);
            return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
        };

        function getSheet(exportData, opts) {
            var ws = {};
            var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
            for(var R = 0; R != $scope.exportData.length; ++R) {
                for(var C = 0; C != $scope.exportData[R].length; ++C) {
                    if(range.s.r > R) range.s.r = R;
                    if(range.s.c > C) range.s.c = C;
                    if(range.e.r < R) range.e.r = R;
                    if(range.e.c < C) range.e.c = C;
                    var cell = {v: $scope.exportData[R][C] };
                    if(cell.v == null) continue;
                    var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

                    if(typeof cell.v === 'number') cell.t = 'n';
                    else if(typeof cell.v === 'boolean') cell.t = 'b';
                    else if(cell.v instanceof Date) {
                        cell.t = 'n'; cell.z = XLSX.SSF._table[14];
                        cell.v = datenum(cell.v);
                    }
                    else cell.t = 's';

                    ws[cell_ref] = cell;
                }
            }
            if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
            return ws;
        };
        function Workbook() {
            if(!(this instanceof Workbook)) return new Workbook();
            this.SheetNames = [];
            this.Sheets = {};
        }
        var wb = new Workbook(), ws = getSheet($scope.exportData);
        /* add worksheet to workbook */
        wb.SheetNames.push('sampleFile');
        wb.Sheets['sampleFile'] = ws;
        var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'});

        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
        saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), $scope.fileName+'.xlsx');
    };
});

html代码:

<button class="btn btn-primary btn-ef btn-ef-3 btn-ef-3c mb-10" ng-click="download()">Export <i class="fa fa-download"></i></button>

已缓存的链接:Angular excel export

我尝试使用$timeout生成excel以便从后端获取数据,但生成的excel仍为空白。

1 个答案:

答案 0 :(得分:0)

您可以尝试按照代码更改进行操作。你需要推动改变 收到后端的回复

$scope.exportData
myApp.controller('modalCtrlTest', function ($scope, UserService) {
    $scope.exportData = [];

    $scope.allDataInfomation = function(){
        UserService.getDataFromBackEnd().then(
        function(response){
          $scope.jsonToExport = response;
          $scope.fileName = "report";  // need to push data here after response
          $scope.exportData.push(["#", "Movie", "Actor"]);
            angular.forEach($scope.jsonToExport, function(value, key) {
                $scope.exportData.push([value.mID, value.mName, value.mActor]);
            });
            $scope.createExcelData();
        });         
    }

    //export button directive code
    $scope.download = function() {  //This method is called when clicked on the Export  button

        $scope.allDataInfomation();
    }
    $scope.createExcelData = function() {
        function datenum(v, date1904) {
            if(date1904) v+=1462;
            var epoch = Date.parse(v);
            return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
        };

        function getSheet(exportData, opts) {
            var ws = {};
            var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
            for(var R = 0; R != $scope.exportData.length; ++R) {
                for(var C = 0; C != $scope.exportData[R].length; ++C) {
                    if(range.s.r > R) range.s.r = R;
                    if(range.s.c > C) range.s.c = C;
                    if(range.e.r < R) range.e.r = R;
                    if(range.e.c < C) range.e.c = C;
                    var cell = {v: $scope.exportData[R][C] };
                    if(cell.v == null) continue;
                    var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

                    if(typeof cell.v === 'number') cell.t = 'n';
                    else if(typeof cell.v === 'boolean') cell.t = 'b';
                    else if(cell.v instanceof Date) {
                        cell.t = 'n'; cell.z = XLSX.SSF._table[14];
                        cell.v = datenum(cell.v);
                    }
                    else cell.t = 's';

                    ws[cell_ref] = cell;
                }
            }
            if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
            return ws;
        };
        function Workbook() {
            if(!(this instanceof Workbook)) return new Workbook();
            this.SheetNames = [];
            this.Sheets = {};
        }
        var wb = new Workbook(), ws = getSheet($scope.exportData);
        /* add worksheet to workbook */
        $scope.exportData.length = 0;
        wb.SheetNames.push('sampleFile');
        wb.Sheets['sampleFile'] = ws;
        var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'});

        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
        saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), $scope.fileName+'.xlsx');
    };
});

<button class="btn btn-primary btn-ef btn-ef-3 btn-ef-3c mb-10" ng-click="download()">Export <i class="fa fa-download"></i></button>