web-dev-qa-db-fra.com

Comment exporter ou convertir JSON vers Excel dans AngularJS?

J'extrais un tableau avec 4 objets et chaque objet a un tableau à l'intérieur, à partir de la source de données de mon graphique de kendo, sur mon projet Angular.

La taille des données à l'intérieur de chaque sous-objet varie, mais il inclut toujours un horodatage et 1 à 5 champs de valeur.

J'ai besoin d'exporter ce tableau dans un fichier Excel (.xls ou .xlsx NOT CSV).

Jusqu'ici, j'ai réussi à télécharger le JSON sous forme de fichier (les fichiers .json et .xls non formatés).

J'aimerais que chaque objet soit un livre et que, dans ce livre, la mise en forme comporte l'horodatage dans la première colonne, la valeur 1 dans un autre, etc. L'en-tête des colonnes doit être timestamp, value1 name, etc. (je traduis ces informations sur l'interface utilisateur en fonction des préférences de l'utilisateur).

Comment puis-je construire ce type de fichier .xls formaté en utilisant angular? Je ne connais pas de bonne bibliothèque particulière pour cela, c'est clair sur la façon de l'utiliser dans Angular.

4
mesosteros

Après suggestion de lien de Nathan Beck , j'ai utilisé AlaSQL. Je reçois des colonnes correctement formatées, il suffit d’adapter mon tableau pour avoir plusieurs feuilles de calcul.

Nous intégrons alaSQL dans notre projet Angular en incluant les fichiers alasql.min.js et xlsx.core.min.js.

Ensuite, nous appelons la méthode alasql dans notre fonction

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

EDIT: Résolution des problèmes liés aux multiples feuilles de calcul. Gardez à l'esprit que lorsque vous utilisez la méthode de feuille de calcul multiple, vous devez supprimer l'astérisque et remplacer les en-têtes: objet true dans la requête par un point d'interrogation, en passant les options dans un tableau séparé. Alors:

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]);
6
mesosteros

Directive angulaire pour l'exportation et le téléchargement de JSON au format CSV. Effectuez bower installez ng-csv-download . Run 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>

1

Vous pouvez utiliser la bibliothèqueXLSXpour convertir JSON en fichier XLS et télécharger . Créez simplement un service pour votre application AngularJS, puis appelez-le en tant que méthode de service ayant le code ci-dessous.

J'ai trouvé ce tutoriel avec le code JS et jQuery mais nous pouvons nous référer à ce code pour l'utiliser dans AngularJS 

Travailler Démo

Source link

Méthode

bibliothèque d'inclusion

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

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());
0
Code Spy