如何将 JSON 导出或转换为 AngularJS 中的 Excel?

How to export or convert JSON to Excel in AngularJS?

我正在提取一个包含 4 object 的数组,每个 object 内部都有一个数组,来自我的 kendo 图表数据源,在我的 Angular 项目中。

每个 sub-object 中的数据大小不一,但始终包含一个时间戳和 1-5 个值字段。

我需要将此数组导出到 Excel 文件(.xls 或 .xlsx 不是 CSV)。

到目前为止,我设法将 JSON 作为文件单独下载(.json 和未格式化的 .xls)。

我希望每个 object 都是一本书,并且在那本书中有一个格式,在第一列中有时间戳,在另一列中有值 1,依此类推。列的 header 应该是时间戳、value1 名称等(我根据用户偏好在 ui 上翻译这些)。

如何使用 angular 生成 uild 这种格式化的 .xls 文件?我不知道一个特别好的库,在 Angular.

中清楚地说明了如何使用它

Nathan Beck's link sugestion之后,我使用了AlaSQL。我的列格式正确,只需要调整我的数组以包含多个工作表。

我们将 alaSQL 集成到我们的 Angular 项目中的方法是包含 alasql.min.js 和 xlsx.core.min.js。

然后在我们的函数中调用alasql方法

$scope.export = function(){
var arrayToExport = [{id:1, name:"gas"},...];
  alasql('SELECT * INTO XLSX("your_filename.xlsx",{headers:true}) FROM ?', arrayToExport);
}

编辑: 也解决了多个工作表问题。请记住,在使用多工作表方法时,您必须删除星号并将查询中的 headers: true 对象替换为问号,将选项传递到单独的数组中。所以:

var arrayToExport1 = [{id:1, name:"gas"},...];
var arrayToExport2 = [{id:1, name:"solid"},...];
var arrayToExport3 = [{id:1, name:"liquid"},...];
var finalArray = arrayToExport1.concat(arrayToExport2, arrayToExport3);

var opts = [{sheetid: "gas", headers: true},{sheetid: "solid", headers: true},{sheetid: "liquid", headers: true}];
alasql('SELECT INTO XLSX("your_filename.xlsx",?) FROM ?', [opts, finalArray]);

Angular 指令,用于将 JSON 导出和下载为 CSV。执行 bower 安装 ng-csv-downloadRun in plunkr

var app = angular.module('testApp', ['tld.csvDownload']);

app.controller('Ctrl1', function($scope, $rootScope) {
    $scope.data = {};

    $scope.data.exportFilename = 'example.csv';
    $scope.data.displayLabel = 'Download Example CSV';
    $scope.data.myHeaderData = {
        id: 'User ID',
        name: 'User Name (Last, First)',
        alt: 'Nickname'
    };
    $scope.data.myInputArray = [{
        id: '0001',
        name: 'Jetson, George'
    }, {
        id: '0002',
        name: 'Jetson, Jane',
        alt: 'Jane, his wife.'
    }, {
        id: '0003',
        name: 'Jetson, Judith',
        alt: 'Daughter Judy'
    }, {
        id: '0004',
        name: 'Jetson, Elroy',
        alt: 'Boy Elroy'
    }, {
        id: 'THX1138',
        name: 'Rosie The Maid',
        alt: 'Rosie'
    }];

});
<!DOCTYPE html>
<html ng-app="testApp">

  <head>
    <meta charset="utf-8" />
    <title>Exporting JSON as a CSV</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
    <script src="csv-download.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body>
<div>Using an <a href="https://github.com/pcimino/csv-download" target="_blank">Angular directive for exporting JSON data as a CSV download.</a></div>


<div ng-controller="Ctrl1">
    <h2>All Attributes Set</h2>
    <csv-download
            filename="{{data.exportFilename}}"
            label="{{data.displayLabel}}"
            column-header="data.myHeaderData"
            input-array="data.myInputArray">
    </csv-download>

    <hr />
    <h2>Only Required Attribute Set</h2>
    <h3>Optional Attributes Default</h3>
    <csv-download
            input-array="data.myInputArray">
    </csv-download>
</div>
  </body>

</html>

您可以使用 XLSX 库将 JSON 转换为 XLS 文件并下载。只需为您的 AngularJS 应用程序创建一个服务,然后将其作为具有以下代码的服务方法调用。

我发现本教程有 JS 和 jQuery 代码,但我们可以参考此代码在 AngularJS

中使用

工作Demo

来源link

方法

包含库

<script type="text/javascript" src="//unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

JavaScript代码

    var createXLSLFormatObj = [];

    /* XLS Head Columns */
    var xlsHeader = ["EmployeeID", "Full Name"];

    /* XLS Rows Data */
    var xlsRows = [{
            "EmployeeID": "EMP001",
            "FullName": "Jolly"
        },
        {
            "EmployeeID": "EMP002",
            "FullName": "Macias"
        },
        {
            "EmployeeID": "EMP003",
            "FullName": "Lucian"
        },
        {
            "EmployeeID": "EMP004",
            "FullName": "Blaze"
        },
        {
            "EmployeeID": "EMP005",
            "FullName": "Blossom"
        },
        {
            "EmployeeID": "EMP006",
            "FullName": "Kerry"
        },
        {
            "EmployeeID": "EMP007",
            "FullName": "Adele"
        },
        {
            "EmployeeID": "EMP008",
            "FullName": "Freaky"
        },
        {
            "EmployeeID": "EMP009",
            "FullName": "Brooke"
        },
        {
            "EmployeeID": "EMP010",
            "FullName": "FreakyJolly.Com"
        }
    ];


    createXLSLFormatObj.push(xlsHeader);
    $.each(xlsRows, function(index, value) {
        var innerRowData = [];
        $("tbody").append('<tr><td>' + value.EmployeeID + '</td><td>' + value.FullName + '</td></tr>');
        $.each(value, function(ind, val) {

            innerRowData.push(val);
        });
        createXLSLFormatObj.push(innerRowData);
    });


    /* File Name */
    var filename = "FreakyJSON_To_XLS.xlsx";

    /* Sheet Name */
    var ws_name = "FreakySheet";

    if (typeof console !== 'undefined') console.log(new Date());
    var wb = XLSX.utils.book_new(),
        ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    /* Add worksheet to workbook */
    XLSX.utils.book_append_sheet(wb, ws, ws_name);

    /* Write workbook and Download */
    if (typeof console !== 'undefined') console.log(new Date());
    XLSX.writeFile(wb, filename);
    if (typeof console !== 'undefined') console.log(new Date());