docs.sheetjs.com/docz/docs/03-demos/32-extensions/03-excelapi.md
2023-09-05 14:04:23 -04:00

220 lines
6.4 KiB
Markdown

---
title: Excel JavaScript API
pagination_prev: demos/cloud/index
pagination_next: demos/bigdata/index
---
import current from '/version.js';
import CodeBlock from '@theme/CodeBlock';
:::info pass
This demo focuses on the JavaScript API included with Excel. For reading and
writing Excel files, [other demos](/docs/demos/) cover a wide variety of use cases
:::
Office 2016 introduced a JavaScript API for interacting with the application.
It offers solutions for custom functions as well as task panes.
Excel currently does not provide support for working with Apple Numbers files
and some legacy file formats. SheetJS fills the gap.
This demo creates a new custom function `SHEETJS.EXTERN()` which tries to fetch
an external spreadsheet and insert the data into the worksheet.
![`SHEETJS.EXTERN` output](pathname:///xlapi/xlfetch.png)
This demo focuses on the basic mechanics. Advanced topics like Excel Custom
Function parameters are covered in the official Office JavaScript API docs.
:::note
This demo was last tested on 2023 September 03 against Excel 365 (version 2308)
:::
:::caution Excel Bugs
There was a binary data bug affecting `fetch` and Excel. It was resolved in
version 2303. It is strongly encouraged to upgrade to the latest version of
Excel 365 before running the demo.
:::
## Integration Details
The [NodeJS module](/docs/getting-started/installation/nodejs) can be imported
in an Excel Custom Functions project.
The [`sheet_to_json`](/docs/api/utilities#json) helper function can generate
arrays of arrays of values based on the worksheet data. Excel custom functions
transparently treat these as Dynamic Arrays.
This example fetches a file, parses the data, and extracts the first worksheet:
```js title="src\functions\functions.js"
var XLSX = require("xlsx");
/**
* Download file and write data
* @customfunction
* @param {string} url URL to fetch and parse
* @returns {any[][]} Worksheet data
*/
async function extern(url) {
try {
/* Fetch Data */
const res = await fetch(url);
/* Get Data */
const ab = await res.arrayBuffer();
/* Parse Data */
var wb = XLSX.read(ab);
/* get and return data */
var ws = wb.Sheets[wb.SheetNames[0]]; // get first worksheet
var aoa = XLSX.utils.sheet_to_json(ws, { header: 1 }); // array of arrays
return aoa;
} catch(e) { return [[e.message || e]]; } // pass error back to Excel
}
```
## Complete Demo
0) Clear the functions cache. For the tested version of Excel:
- Open File Explorer
- Select the address bar and enter `%LOCALAPPDATA%\Microsoft\Office\16.0\Wef`
- Delete the `CustomFunctions` folder (if it exists) and empty Recycle Bin.
:::caution pass
**This will delete all custom functions associated with the user account!**
To preserve the custom functions on the user account, rename the existing folder
to `CustomFunctionsBackup` before testing and rename back to `CustomFunctions`
after testing is finished.
:::
1) Install [NodeJS LTS](https://nodejs.org/en/download/).
2) Install dependencies in a new PowerShell window:
```bash
npm i -g yo bower generator-office
```
### Creating a new Add-in
3) Run `yo office` from the command line. It will ask a few questions:
- "Choose a project type": "Excel Custom Functions using a Shared Runtime"
- "Choose a script type": "JavaScript",
- "What do you want to name your add-in?": "SheetJSImport"
4) Start the dev process:
```bash
cd SheetJSImport
npm run build
npm start
```
Running `npm start` will open up a terminal window and a new Excel window with
the loaded add-in. Keep the terminal window open.
5) In `manifest.xml` , search for `Functions.NameSpace` . There will be an XML
element with name `bt:String`. Change the `DefaultValue` attribute to `SHEETJS`:
```xml title="manifest.xml"
<bt:ShortStrings>
// highlight-next-line
<bt:String id="Functions.Namespace" DefaultValue="SHEETJS"/>
<bt:String id="GetStarted.Title" DefaultValue="Get started with your sample add-in!" />
```
6) Close the Excel window and the terminal window, then run `npm start` again.
### Integrating the SheetJS Library
7) Install the SheetJS library in the project
<CodeBlock language="bash">{`\
npm i --save https://cdn.sheetjs.com/xlsx-${current}/xlsx-${current}.tgz`}
</CodeBlock>
8) Replace `src\functions\functions.js` with the following:
```js title="src\functions\functions.js"
var XLSX = require("xlsx");
/**
* Print SheetJS Library Version
* @customfunction
* @returns {string[][]} The SheetJS Library Version.
*/
function version() {
return [[XLSX.version]];
}
```
9) After making the change, save the files. Close the terminal window and the
Excel window (do not save the Excel file). Re-run `npm start`.
10) In the new Excel window, enter the formula `=SHEETJS.VERSION()` in cell
`D1`. You should see something similar to the following screenshot:
![`SHEETJS.VERSION` output](pathname:///xlapi/xlvers.png)
This indicates that the SheetJS library has been loaded.
### Fetching Files from the Internet
11) Add the following code snippet to `src\functions\functions.js`:
```js title="src\functions\functions.js (add to end)"
/**
* Download file and write data
* @customfunction
* @param {string} url URL to fetch and parse
* @returns {any[][]} Worksheet data
*/
async function extern(url) {
try {
/* Fetch Data */
const res = await fetch(url);
/* Get Data */
const ab = await res.arrayBuffer();
/* Parse Data */
var wb = XLSX.read(ab);
/* get and return data */
var ws = wb.Sheets[wb.SheetNames[0]]; // get first worksheet
var aoa = XLSX.utils.sheet_to_json(ws, { header: 1 }); // get data as array of arrays
return aoa;
} catch(e) { return [[e.message || e]]; } // pass error back to Excel
}
```
12) After making the change, save the files. Close the terminal window and the
Excel window (do not save the Excel file). Re-run `npm start`.
13) Enter the text `https://sheetjs.com/pres.numbers` in cell `D1`. Enter the
formula `=SHEETJS.EXTERN(D1)` in cell `D2` and press Enter. Excel should pull
in the data and generate a dynamic array.
:::tip pass
[SheetJS Pro](https://sheetjs.com/pro) offers additional features that can be
used in Excel Custom Functions and Add-ins
:::