【问题标题】:Export data in CSV, Excel, PDF format in AngularJS在 AngularJS 中以 CSV、Excel、PDF 格式导出数据
【发布时间】:2014-06-28 20:38:58
【问题描述】:

我想在我的应用中添加 CSV、Excel、PDF 格式的导出表格数据功能。

我正在使用 angularjs 1.2.16 构建应用程序。

在 Excel 中导出数据

我用过

<script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>

使用以下代码将表格导出为 XLS 格式:

var blob = new Blob([document.getElementById('exportable').innerHTML], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "report.xls");

以上代码运行良好。

以 CSV、PDF 格式导出数据

以同样的方式,我想以 CSV 和 PDF 格式导出数据。
我使用http://www.directiv.es/ng-csv 以 CSV 格式导出数据,但在 ubuntu libre office 中无法正常工作(文件显示数据损坏)。
谁能告诉我如何在angularjs中导出CSV、Excel和PDF格式的表格数据?

【问题讨论】:

    标签: javascript angularjs excel pdf


    【解决方案1】:

    如果您对 CSV 文件感到满意,那么 ngCsv 模块就是您的最佳选择。您不从 DOM 加载元素,而是直接导出数组。在这里,您可以看到正在运行的 ngCsv 示例。

    html:

     <h2>Export {{sample}}</h2>
      <div>
          <button type="button" ng-csv="getArray" filename="test.csv">Export</button>
    </div>
    

    和js:

    angular.module('csv', ['ngCsv']);
    
    function Main($scope) {
        $scope.sample = "Sample";
        $scope.getArray = [{a: 1, b:2}, {a:3, b:4}];                            
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用Alasql JavaScript 库和XLSX.js 将数据从 AngularJS 导出为 XLS、XLSX、CSV 和 TAB 格式。

      在代码中包含两个库:

      要将数据导出为 Excel 格式,请在控制器代码中创建一个函数:

      function myCtrl($scope) {
          $scope.exportData = function () {
             alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?',[$scope.items]);
          };
          $scope.items = [{a:1,b:10},{a:2,b:20},{a:3,b:30}];
      };
      

      然后在 HTML 中创建一个按钮(或任何其他链接):

      <div ng-controller="myCtrl">
          <button ng-click="exportData()">Export</button>
      </div>
      

      在 jsFiddle 中尝试this example

      要将数据保存为 CSV 格式,请使用 CSV() 函数:

      alasql("SELECT * INTO CSV('mydata.csv', {headers:true}) FROM ?",[$scope.mydata]);
      

      或使用 TXT()、CSV()、TAB()、XLS()、XLSX() 函数获取正确的文件格式。

      【讨论】:

      • 很奇怪...是Mac下用Chrome开发的,我也在另一台电脑上用Win8测试过。你有什么版本的 Chrome?我的是 39.0.2171.71(64 位)。您是否从 jsFiddle jsfiddle.net/agershun/00nfeq12 运行了示例
      • 嘿,我有一个问题。您能否提供一些细节,它如何在没有服务器调用的情况下创建文件?
      • 我使用 FileSaver 库 (github.com/eligrey/FileSaver.js)。此外,您可以查看 Alasql 实用程序库,其中包含在节点和浏览器中加载和保存文件的功能 (github.com/agershun/alasql/blob/version-0.0.36/src/15utility.js)
      • 如何导出pdf文件?你有推荐的图书馆吗?
      【解决方案3】:

      另存为;要更改注册的文件扩展名,例如:“f:\folder\report.html”目录?

      var blob = new Blob([document.getElementById('exportable').innerHTML], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" }); 
      saveAs(blob, "report.xls");
      

      【讨论】:

      • 知道如何转义分号等字符吗?
      【解决方案4】:

      我已经尝试了几种方法并得出以下结论,类型安全(DefinitelyTyped):

         exportAsExcel(tableId: string, fileName: string, linkElement: any) {
      
      
      
              var uri = 'data:application/vnd.ms-excel;base64,',
                  template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                  base64 = function (s) {
                      return window.btoa(decodeURI(encodeURIComponent(s)));
                  },
      
                  format = function (s, c) {
                      return s.replace(/{(\w+)}/g, function (m, p) {
                          return c[p];
                      });
                  };
              // get the table data
              var table = document.getElementById(tableId);
              var ctx = {
                  worksheet: fileName,
                  table: table.innerHTML
              };
              // if browser is IE then save the file as blob, tested on IE10 and IE11
              var browser = window.navigator.appVersion;
              if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) ||
                  (browser.indexOf('MSIE 10') !== -1)) {
                  var builder = new MSBlobBuilder(); 
                  builder.append(uri + format(template, ctx));
                  var blob = builder.getBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
                  window.navigator.msSaveBlob(blob, fileName + '.xlsx'); 
              } else {
                  var element = document.getElementById(linkElement);
                  var a = document.createElement('a');
                  a.href = uri + base64(format(template, ctx));
                  a.target = '_blank';
                  a.setAttribute('download', fileName + '.xlsx');
                  document.body.appendChild(a);
                  a.click();
      
              }
              toastr.success("Awesome!", "We've created an Excel report for you and you should get it as a download in your browser.");
          }
      

      感谢那些在各种文章中做出贡献的人。s

      【讨论】:

        【解决方案5】:

        我们可以将表格中的数据导出为各种格式,包括 Json, Xml, Pdf .....

        你可以找到详细的解释http://www.prathapkudupublog.com/2015/10/angular-export-to-table.html 注意:此实现不会在 IE 中运行

        你需要什么? Angularjs jQuery.js 下面引用的文件 tableExport.js,JqueryBase64.js,html2canvas.js,base64.js,Jspdf.js,sprintf.js

         <script type="text/javascript">
            var myAppModule = angular.module('myApp', []);
            myAppModule.controller('myCtrl', function ($scope) {
                $scope.exportData = function () {
                    $('#customers').tableExport({ type: 'json', escape: 'false' });
                };
                $scope.items = [
                    {
                        "FirstName": "Prathap",
                        "LastName": "Kudupu",
                        "Address": "Near Anjana Beach"
                    },
                    {
                        "FirstName": "Deepak",
                        "LastName": "Dsouza",
                        "Address": "Near Nariman Point"
                    }
                ];
        
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-24
          • 1970-01-01
          • 2021-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多