docs.sheetjs.com/docz/docs/03-demos/01-frontend/07-angularjs.md
2023-08-28 18:40:53 -04:00

9.2 KiB

title pagination_prev pagination_next sidebar_position
AngularJS demos/index demos/grid/index 7

import current from '/version.js'; import CodeBlock from '@theme/CodeBlock';

:::warning pass

This demo is for the legacy AngularJS framework (version 1).

"Angular" now commonly refers to the new framework starting with version 2. The "Angular" demo covers the new framework.

:::

AngularJS is a JS library for building user interfaces.

Demo

:::note

This demo was last run on 2023 August 27 using AngularJS 1.8.2

:::

Click here for a live standalone integration demo.

The demo uses an array of objects as its internal state. It fetches and displays data on load. It also includes a button for exporting data to file and a file input element for loading user-submitted files.

Installation

The Standalone scripts can be referenced in a SCRIPT tag from the HTML entrypoint page.

The $http service can request binary data using "arraybuffer" response type. This maps to the "array" input format for XLSX.read:

app.controller('sheetjs', function($scope, $http) {
  $http({
    method:'GET', url:'https://sheetjs.com/pres.xlsx',
    // highlight-next-line
    responseType:'arraybuffer'
  }).then(function(data) {
    // highlight-next-line
    var wb = XLSX.read(data.data, {type:"array"});
    /* DO SOMETHING WITH wb HERE */
    $scope.data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
  }, function(err) { console.log(err); });
});
Parsing User-Submitted Files (click to show)

For file input elements, a general import directive is fairly straightforward:

  1. Add an INPUT element with attribute import-sheet-js="":
<input type="file" import-sheet-js="" multiple="false"  />
  1. Define the SheetJSImportDirective directive function:
function SheetJSImportDirective() { return {
  scope: false,
  link: function ($scope, $elm) {
    $elm.on('change', function (changeEvent) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var wb = XLSX.read(e.target.result);

        /* DO SOMETHING WITH wb HERE */
        $scope.apply(function() {
          $scope.data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        });
      };
      reader.readAsArrayBuffer(changeEvent.target.files[0]);
    });
  }
}; }
  1. Define the importSheetJs directive in the app:
app.directive("importSheetJs", [SheetJSImportDirective]);

Internal State

The various SheetJS APIs work with various data shapes. The preferred state depends on the application.

Array of Objects

Typically, some users will create a spreadsheet with source data that should be loaded into the site. This sheet will have known columns. For example, our presidents sheet has "Name" / "Index" columns:

pres.xlsx data

This naturally maps to an array of typed objects, as in the example below:

app.controller('sheetjs', function($scope, $http) {
  $http({ method:'GET', url:'https://sheetjs.com/pres.xlsx', responseType:'arraybuffer' }).then(function(data) {
    var wb = XLSX.read(data.data, {type:"array"});
    // highlight-next-line
    $scope.data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
  }, function(err) { console.log(err); });
});

data will be an array of objects:

[
  { Name: "Bill Clinton", Index: 42 },
  { Name: "GeorgeW Bush", Index: 43 },
  { Name: "Barack Obama", Index: 44 },
  { Name: "Donald Trump", Index: 45 },
  { Name: "Joseph Biden", Index: 46 }
]

A component will typically loop over the data using ng-repeat. The following template generates a TABLE with a row for each President:

<table id="sjs-table">
  <tr><th>Name</th><th>Index</th></tr>
  <tr ng-repeat="row in data track by $index">
    <td>{{row.Name}}</td>
    <td>{{row.Index}}</td>
  </tr>
</table>

XLSX.utils.json_to_sheet can generate a worksheet from the data:

/* assuming $scope.data is an array of objects */
$scope.exportSheetJS = function() {
  /* generate a worksheet */
  var ws = XLSX.utils.json_to_sheet($scope.data);
  /* add to workbook */
  var wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Presidents");
  /* write workbook and force a download */
  XLSX.writeFile(wb, "SheetJSAngularJSAoO.xlsx");
};
Complete Example (click to show)
  1. Save the following to index.html:

{`\

<html ng-app="s5s"> <head> </head>

SheetJS + AngularJS demo

\n\
Export Table
NameIndex
{{row.Name}} {{row.Index}}
\n\ </html>`}
  1. Start a local web server with npx http-server . and access the displayed URL with a web browser (typically http://localhost:8080)

HTML

The main disadvantage of the Array of Objects approach is the specific nature of the columns. For more general use, passing around an Array of Arrays works. However, this does not handle merge cells well!

The sheet_to_html function generates HTML that is aware of merges and other worksheet features. The generated HTML does not contain any <script> tags, and should therefore be safe to pass to an ng-bind-html binding. This approach requires the ngSanitize plugin.

<div ng-controller="sheetjs">
  <!-- highlight-next-line -->
  <div ng-bind-html="data" id="tbl"></div>
</div>

<script>
// highlight-next-line
var app = angular.module('s5s', ['ngSanitize']);
app.controller('sheetjs', function($scope, $http) {
  $http({ method:'GET', url:'https://sheetjs.com/pres.xlsx', responseType:'arraybuffer' }).then(function(data) {
    var wb = XLSX.read(data.data, {type:"array"});
    // highlight-next-line
    $scope.data = XLSX.utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]);
  }, function(err) { console.log(err); });
});
</script>

The HTML table can be directly exported with XLSX.utils.table_to_book:

  $scope.exportSheetJS = function() {
    /* export table element */
    // highlight-start
    var tbl = document.getElementById("tbl").getElementsByTagName("TABLE")[0];
    var wb = XLSX.utils.table_to_book(tbl);
    // highlight-end
    XLSX.writeFile(wb, "SheetJSAngularJSHTML.xlsx");
  };
Complete Example (click to show)
  1. Save the following to index.html:

{`\

<html ng-app="s5s"> <head> </head>

SheetJS + AngularJS demo

\n\
Export Table
\n\ </html>`}
  1. Start a local web server with npx http-server . and access the displayed URL with a web browser (typically http://localhost:8080)