docs.sheetjs.com/docz/docs/03-demos/02-frontend/07-angularjs.md

394 lines
12 KiB
Markdown
Raw Normal View History

2023-04-09 00:20:50 +00:00
---
2023-11-19 05:23:07 +00:00
title: Sheets in AngularJS Sites
sidebar_label: AngularJS
description: Build interactive websites with AngularJS. Seamlessly integrate spreadsheets into your app using SheetJS. Bring Excel-powered workflows and data to the modern web.
2023-04-09 00:20:50 +00:00
pagination_prev: demos/index
pagination_next: demos/grid/index
sidebar_position: 7
---
2023-05-03 03:40:40 +00:00
import current from '/version.js';
import CodeBlock from '@theme/CodeBlock';
2023-08-28 22:40:53 +00:00
:::warning pass
2023-04-09 00:20:50 +00:00
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](/docs/demos/frontend/angular) covers the new framework.
:::
2023-08-18 20:39:12 +00:00
[AngularJS](https://angularjs.org/) is a JS library for building user interfaces.
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
[SheetJS](https://sheetjs.com) is a JavaScript library for reading and writing
data from spreadsheets.
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
This demo uses AngularJS and SheetJS to process and generate spreadsheets. We'll
explore how to load SheetJS in AngularJS projects and compare common state
models and data flow strategies.
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
## Live Demo
:::note Tested Deployments
2023-12-05 03:46:54 +00:00
This demo was tested in the following environments:
| Version | Date |
|:------------------|:-----------|
| `1.8.2` (latest) | 2023-12-04 |
| `1.2.32` (legacy) | 2023-12-04 |
2023-04-09 00:20:50 +00:00
:::
[Click here for a live standalone integration demo.](pathname:///angularjs/)
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
2023-09-22 06:32:55 +00:00
The [SheetJS Standalone scripts](/docs/getting-started/installation/standalone)
can be referenced in a `SCRIPT` tag from the HTML entry point page.
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
The script adds the `XLSX` global variable.
## Data Sources
Modern browsers support a number of convenient APIs for receiving files and
allowing users to submit files.
AngularJS, relevant in an era before the APIs were available, provides wrappers
to simplify network and file processing.
### Remote Files
To download files from a remote location, the `$http` service can perform GET
requests[^1]
The `responseType` option is directly passed to `XMLHttpRequest`. Setting the
property to `"arraybuffer"` ensures the result is an `ArrayBuffer` object.
The SheetJS [`read`](/docs/api/parse-options) method can parse the `ArrayBuffer`
and return a SheetJS workbook object[^2].
The following controller fetches [a sample file](https://sheetjs.com/pres.xlsx),
parses the result into a workbook, extracts the first worksheet, and uses the
SheetJS [`sheet_to_html`](/docs/api/utilities/html#html-table-output) method to
generate a HTML table:
2023-04-09 00:20:50 +00:00
```js
2023-11-19 05:23:07 +00:00
/* The controller function must accept a `$http` argument */
2023-04-09 00:20:50 +00:00
app.controller('sheetjs', function($scope, $http) {
2023-11-19 05:23:07 +00:00
/* fetch https://sheetjs.com/pres.xlsx */
2023-04-09 00:20:50 +00:00
$http({
method:'GET', url:'https://sheetjs.com/pres.xlsx',
2023-11-19 05:23:07 +00:00
/* ensure the result is an ArrayBuffer object */
2023-04-09 00:20:50 +00:00
responseType:'arraybuffer'
}).then(function(data) {
// highlight-next-line
2023-11-19 05:23:07 +00:00
var wb = XLSX.read(data.data);
/* generate HTML from first worksheet*/
var ws = wb.Sheets[wb.SheetNames[0]];
var html = XLSX.utils.sheet_to_html(ws);
/* assign to the `tbl` scope property */
$scope.tbl = html;
2023-04-09 00:20:50 +00:00
}, function(err) { console.log(err); });
});
```
2023-11-19 05:23:07 +00:00
### User-Submitted Files
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
Users can submit files using HTML file input elements. A DOM `change` event is
created when users select a file.
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
In AngularJS, standard DOM event handlers are created using custom directives
with the `link` option[^3].
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
The following directive function creates a `change` event handler that will use
a `FileReader` to generate an `ArrayBuffer` object with the file data, parse the
file data using the SheetJS [`read`](/docs/api/parse-options) method, generate a
HTML table using [`sheet_to_html`](/docs/api/utilities/html#html-table-output),
and store the result in the `tbl` property of the app state:
2023-04-09 00:20:50 +00:00
```js
function SheetJSImportDirective() { return {
scope: false,
2023-11-19 05:23:07 +00:00
/* $elm will be a reference to the file input DOM element */
2023-04-09 00:20:50 +00:00
link: function ($scope, $elm) {
2023-11-19 05:23:07 +00:00
/* add a `change` event handler */
2023-04-09 00:20:50 +00:00
$elm.on('change', function (changeEvent) {
2023-11-19 05:23:07 +00:00
/* use a FileReader to read the file */
2023-04-09 00:20:50 +00:00
var reader = new FileReader();
reader.onload = function (e) {
2023-11-19 05:23:07 +00:00
/* this event handler will be called once the data is read */
2023-04-09 00:20:50 +00:00
var wb = XLSX.read(e.target.result);
2023-11-19 05:23:07 +00:00
/* generate HTML from first worksheet*/
var ws = wb.Sheets[wb.SheetNames[0]];
var html = XLSX.utils.sheet_to_html(ws);
/* assign to the `tbl` scope property */
$scope.apply(function() { $scope.tbl = html; });
2023-04-09 00:20:50 +00:00
};
2023-11-19 05:23:07 +00:00
/* read */
2023-04-09 00:20:50 +00:00
reader.readAsArrayBuffer(changeEvent.target.files[0]);
});
}
}; }
```
2023-11-19 05:23:07 +00:00
This functionality can be added to the app in two steps:
1) Add an `INPUT` element with attribute `import-sheet-js=""`:
```html
<input type="file" import-sheet-js="" multiple="false" />
```
2) Define the `importSheetJs` directive that attaches `SheetJSImportDirective`:
2023-04-09 00:20:50 +00:00
```js
app.directive("importSheetJs", [SheetJSImportDirective]);
```
2023-11-19 05:23:07 +00:00
:::note pass
AngularJS normalizes the hyphenated attribute `import-sheet-js` to the
`importSheetJs` camel-case directive name.
:::
2023-04-09 00:20:50 +00:00
## Internal State
The various SheetJS APIs work with various data shapes. The preferred state
depends on the application.
### Array of Objects
2023-11-19 05:23:07 +00:00
The example [presidents sheet](https://sheetjs.com/pres.xlsx) has one header row
with "Name" and "Index" columns. The natural JS representation is an object for
each row, using the values in the first rows as keys:
2023-04-09 00:20:50 +00:00
2024-04-12 01:04:37 +00:00
<table>
<thead><tr><th>Spreadsheet</th><th>State</th></tr></thead>
<tbody><tr><td>
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
![`pres.xlsx` data](pathname:///pres.png)
2023-04-09 00:20:50 +00:00
2023-11-19 05:23:07 +00:00
</td><td>
2023-04-09 00:20:50 +00:00
```js
[
{ 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 }
]
```
2023-11-19 05:23:07 +00:00
</td></tr></tbody></table>
The SheetJS [`sheet_to_json`](/docs/api/utilities/array#array-output) method
generates row objects from worksheets. The following controller parses a remote
file, generates row objects, and stores the array in the state:
```js
app.controller('sheetjs', function($scope, $http) {
$http({
url:'https://sheetjs.com/pres.xlsx',
method:'GET', responseType:'arraybuffer'
}).then(function(data) {
var wb = XLSX.read(data.data);
// highlight-next-line
$scope.data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
}, function(err) { console.log(err); });
});
```
2023-04-09 00:20:50 +00:00
A component will typically loop over the data using `ng-repeat`. The following
template generates a TABLE with a row for each President:
```html
<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>
```
2023-11-19 05:23:07 +00:00
The [`json_to_sheet`](/docs/api/utilities/array#array-of-objects-input) method
can generate a worksheet from the data:
2023-04-09 00:20:50 +00:00
```js
/* 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");
};
```
<details>
<summary><b>Complete Example</b> (click to show)</summary>
2023-04-09 00:20:50 +00:00
1) Save the following to `index.html`:
2023-05-03 03:40:40 +00:00
<CodeBlock language="html" title="index.html">{`\
2023-04-09 00:20:50 +00:00
<!DOCTYPE html>
<html ng-app="s5s">
<head>
<title>SheetJS + AngularJS</title>
2023-08-28 22:40:53 +00:00
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
2023-05-03 03:40:40 +00:00
<script src="https://cdn.sheetjs.com/xlsx-${current}/package/dist/shim.min.js"></script>
<script src="https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min.js"></script>
2023-04-09 00:20:50 +00:00
</head>
<body>
<h3><a href="https://sheetjs.com">SheetJS + AngularJS demo</a></h3>
2023-05-03 03:40:40 +00:00
\n\
2023-04-09 00:20:50 +00:00
<div ng-controller="sheetjs">
<button ng-click="exportSheetJS()">Export Table</button>
<table id="s5s-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>
</div>
2023-05-03 03:40:40 +00:00
\n\
2023-04-09 00:20:50 +00:00
<script>
var app = angular.module('s5s', []);
app.controller('sheetjs', function($scope, $http) {
$scope.exportSheetJS = function() {
var ws = XLSX.utils.json_to_sheet($scope.data);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Presidents");
XLSX.writeFile(wb, "SheetJSAngularJSAoO.xlsx");
};
$http({
url:'https://sheetjs.com/pres.xlsx',
2023-11-19 05:23:07 +00:00
method:'GET', responseType:'arraybuffer'
2023-04-09 00:20:50 +00:00
}).then(function(data) {
2023-11-19 05:23:07 +00:00
var wb = XLSX.read(data.data);
2023-04-09 00:20:50 +00:00
var data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
$scope.data = data;
}, function(err) { console.log(err); });
});
</script>
</body>
2023-05-03 03:40:40 +00:00
</html>`}
</CodeBlock>
2023-04-09 00:20:50 +00:00
2) Start a local web server with `npx http-server .` and access the displayed
URL with a web browser (typically `http://localhost:8080`)
</details>
### 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
2023-12-05 03:46:54 +00:00
requires the `ngSanitize` plugin[^4].
2023-04-09 00:20:50 +00:00
```html
<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) {
2023-11-19 05:23:07 +00:00
$http({
url:'https://sheetjs.com/pres.xlsx',
method:'GET', responseType:'arraybuffer'
}).then(function(data) {
var wb = XLSX.read(data.data);
2023-04-09 00:20:50 +00:00
// highlight-next-line
$scope.data = XLSX.utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]);
}, function(err) { console.log(err); });
});
</script>
```
2023-11-19 05:23:07 +00:00
The HTML table can be directly exported with [`table_to_book`](/docs/api/utilities/html#html-table-input):
2023-04-09 00:20:50 +00:00
```js
$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");
};
```
<details>
<summary><b>Complete Example</b> (click to show)</summary>
2023-04-09 00:20:50 +00:00
1) Save the following to `index.html`:
2023-05-03 03:40:40 +00:00
<CodeBlock language="html" title="index.html">{`\
2023-04-09 00:20:50 +00:00
<!DOCTYPE html>
<html ng-app="s5s">
<head>
<title>SheetJS + AngularJS</title>
2023-08-28 22:40:53 +00:00
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-sanitize.js"></script>
2023-05-03 03:40:40 +00:00
<script src="https://cdn.sheetjs.com/xlsx-${current}/package/dist/shim.min.js"></script>
<script src="https://cdn.sheetjs.com/xlsx-${current}/package/dist/xlsx.full.min.js"></script>
2023-04-09 00:20:50 +00:00
</head>
<body>
<h3><a href="https://sheetjs.com">SheetJS + AngularJS demo</a></h3>
2023-05-03 03:40:40 +00:00
\n\
2023-04-09 00:20:50 +00:00
<div ng-controller="sheetjs">
<button ng-click="exportSheetJS()">Export Table</button>
<div ng-bind-html="data" id="tbl"></div>
</div>
2023-05-03 03:40:40 +00:00
\n\
2023-04-09 00:20:50 +00:00
<script>
var app = angular.module('s5s', ['ngSanitize']);
app.controller('sheetjs', function($scope, $http) {
$scope.exportSheetJS = function() {
var tbl = document.getElementById("tbl").getElementsByTagName("TABLE")[0];
var wb = XLSX.utils.table_to_book(tbl);
XLSX.writeFile(wb, "SheetJSAngularJSHTML.xlsx");
};
$http({
url:'https://sheetjs.com/pres.xlsx',
2023-11-19 05:23:07 +00:00
method:'GET', responseType:'arraybuffer'
2023-04-09 00:20:50 +00:00
}).then(function(data) {
2023-11-19 05:23:07 +00:00
var wb = XLSX.read(data.data);
2023-04-09 00:20:50 +00:00
$scope.data = XLSX.utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]);
}, function(err) { console.log(err); });
});
</script>
</body>
2023-05-03 03:40:40 +00:00
</html>`}
</CodeBlock>
2023-04-09 00:20:50 +00:00
2) Start a local web server with `npx http-server .` and access the displayed
URL with a web browser (typically `http://localhost:8080`)
</details>
2023-11-19 05:23:07 +00:00
[^1]: See [`$http`](https://docs.angularjs.org/api/ng/service/$http) in the AngularJS documentation.
[^2]: See ["Workbook Object"](/docs/csf/book)
2023-12-05 03:46:54 +00:00
[^3]: See ["Creating Directives"](https://docs.angularjs.org/guide/directive#creating-a-directive-that-manipulates-the-dom) in the AngularJS documentation.
[^4]: See [`ngSanitize`](https://docs.angularjs.org/api/ngSanitize) in the AngularJS documentation.