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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39475474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:36:03  来源:igfitidea点击:

How to export or convert JSON to Excel in AngularJS?

javascriptangularjsjsonexcelexport-to-excel

提问by mesosteros

I'm extracting an array with 4 objects and each object has an array inside, from my kendo charts datasource, on my Angular project.

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

The data inside each sub-object varies in size, but it always includes a timestamp, and 1-5 value fields.

每个子对象内的数据大小不同,但始终包含时间戳和 1-5 个值字段。

I need to export this array to an Excel file (.xls or .xlsx NOT CSV).

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

So far I managed to download the JSON as a file on its own (both .json and unformatted .xls).

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

I'd like for each object to be a book and in that book to have a formatting that has the timestamp in the first column, value 1 in another, and so on. The header for the columns should be timestamp, value1 name, etc (I'm translating these on the ui according to user preferences).

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

How can I build this type of formatted .xls file using angular? I don't know a particular good library for this, that is clear on how to use it in Angular.

如何使用 angular 构建这种类型的格式化 .xls 文件?我不知道有什么特别好的库,这很清楚如何在 Angular 中使用它。

回答by mesosteros

Following Nathan Beck's link sugestion, I used AlaSQL. I'm getting correctly formatted columns, just need to adapt my array to have multiple worksheets.

按照Nathan Beck 的链接 sugestion,我使用了 AlaSQL。我得到的列格式正确,只需要调整我的数组即可拥有多个工作表。

The way we integrate alaSQL into our Angular project is by including the alasql.min.js and xlsx.core.min.js.

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

Then we call the alasql method in our function

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

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

EDIT:Solved the multiple worksheets issues as well. Keep in mind that when using the multiple worksheet method, you have to remove the asterisk and replace the headers: true object in the query with a question mark, passing the options in a separate array. So:

编辑:也解决了多个工作表问题。请记住,在使用多工作表方法时,您必须删除星号并将查询中的 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]);

回答by Saniya syed qureshi

Angular directive for exporting and downloading JSON as a CSV. Perform bower install ng-csv-download. Run in plunkr

用于将 JSON 导出和下载为 CSV 的 Angular 指令。执行bower install ng-csv-download在 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>

回答by Code Spy

You can use the XLSXlibrary to convert JSON into XLS file and Download. Just create a service for your AngularJS application then call it as service method having below code.

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

I found this tutorial having JS and jQuery code but we can refer this code to use in AngularJS

我发现这个教程有 JS 和 jQuery 代码,但我们可以参考这段代码在 AngularJS 中使用

Working Demo

工作演示

Source link

源码链接

Method

方法

Include library

包含库

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

JavaScript Code

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());