Angularjs如何在不使用window.location.href的情况下实现导出xls文件

时间:2014-07-03 17:40:11

标签: angularjs

I have a service which returns xls and I want to get & save that xls file dialog 
 when I use 
  ex: window.location.href in jquery its coming but i am forcing to use angularjs

but I dont want to use this **window.location.href** instead of this     

我在不使用window.location.href

的情况下编写下面的angularjs代码

例如:       XLS文件类型主要与Microsoft Corporation的“Excel”相关联。程序:EXCEL.EXE。也由Excel Viewer使用:XLVIEW.EXE。可以通过OpenOffice Suite捕获。注意:此文件类型可能会被感染,如果有人向您发送带有此扩展名的文件,则应仔细扫描。 OpenOffice Suite还可以读取和保存Excel文件。

和上面的描述一样,我需要在angularjs中获得任何示例     这里ajaxFactory是我自己的工厂方法,就像这样

ajaxCommon.factory('ajaxFactory', function ($http) {
 var ajaxFactory = {
 ajaxRequest: function (url, params, method) {
   }
};
return ajaxFactory;
});

 so i am using that method for get the data like below in one angularjs controller
 by invoking that factory inside controller

 The below example used Ajax call for achieve the above window.location.href 
  but i am not  getting can anyone tell solution for this.
ex:
app.controller("Test",["ajaxFactory",function("ajaxFactory"){
   ajaxFactory.ajaxRequest("/app/dao/v5/sample?a=getData",{
      'exportType':'EXPORT_XLS'},"POST").then(function(data){
          var element = angular.element('<a/>');element.attr({
          href: 'data:attachment/vnd.ms-excel,' + data,
          target: '_blank',
          download: 'sample_reports.xls'
          })[0].click();});
     }
     ]);

1 个答案:

答案 0 :(得分:0)

有两种选择:

a)您可以使用Alasql + XLSX.js个库保存Excel文件:

Alasql可以从JavaScript数组生成XLSX文件并将其保存到文件中,如下所示:

function myCtrl(scope) {
    $scope.data = [{a:1},{a:2}];
    alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?',[$scope.data]
}

请参阅jsFiddle的the Angular.js example

b)手工做到&#34;&#34;如果您自己生成Excel文件。包含FileSaver.js库 进入你的项目,然后调用saveAs()函数,如下所示。

    // Create wb spreadsheet object for XLSX.js
    var wbout = XLSX.write(wb,wopts);  // Generate binary file with xlsx data

    saveAs(new Blob([s2ab(wbout)],{type:""}), filename); // Save binary file to file with dialog

    function s2ab(s) {        // Special utility to conert data to ArrayBuffer
      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;
    }