Microsoft Office

Overview

The Excel Adapter exposes a client API which your web apps can use to interoperate with Excel. The io.Connect Excel API provides convenient methods for manipulating Excel features (workbooks, tables, ranges, menus) and enables you to execute various operations in Excel - reading and writing data, subscribing for updates, creating menus dynamically, and more.

⚠️ Note that as version 2 of the Excel Adapter is still an experimental feature, the io.Connect Excel API is currently distributed together with the Excel Adapter bundle in the form of a standalone TypeScript file.

⚠️ Note that for your interop-enabled apps to be able to use the io.Connect Excel API, the Excel Adapter must be installed and Excel must be running.

Excel API Test App

You can use the Excel API testing app hosted at https://interopio.github.io/excel-playground/ to explore the io.Connect Excel API. It provides a convenient way to invoke the exposed methods and get to know the data structures with which they work. It's possible to modify the arguments passed to the methods from the UI of the app and copy entire code snippets which you can them modify and test in the console of the app or in your own interop-enabled app.

The fastest way to start using the Excel API testing app is to:

  1. Copy the app URL - https://interopio.github.io/excel-playground/.
  2. Open the io.Connect Desktop tray menu by right-clicking on the io.Connect Desktop tray icon.
  3. Click on the "Open" menu item.
  4. Paste the URL into the text input field.
  5. Click the "Open" button to start the app in an io.Connect Window.

Another option is to create an app definition for the app and start it from the io.Connect launcher.

Excel Service Operations

The Excel Service API enables your to interoperate with Excel from your interop-enabled web app. The following sections provide examples of using the Excel Service API methods to interact with various Excel features from your app. For detailed information about the Excel Service API methods and data structures, see the API Reference section.

Initialization

To initialize the Excel Service API, instantiate the IOConnectXLService class and pass the initialized API object of the @interopio/desktop library as a required argument:

import IODesktop from "@interopio/desktop";
import { IOConnectXLService } from "./io-excel-service";

// Initializing the `@interopio/desktop` library.
const io = await IODesktop();

// Initializing the Excel Service API.
const xl = new IOConnectXLService(io);

// Now the Excel Service API will be available via the `xl` object.
await xl.openWorkbook("my-workbook.xlsx");

Workbooks

The following sections describe the available operations related to manipulating Excel workbooks.

Create

To create an Excel workbook, use the createWorkbook() method. It accepts a name for the workbook file and a name for the worksheet to create as required arguments. Optionally, you can specify how save conflict resolutions should be handled by using the XLSaveConflictResolution enumeration:

import { XLSaveConflictResolution } from "./io-excel-service";

const workbookName = "My Workbook";
const sheetName = "My Sheet";
const conflictResolution = XLSaveConflictResolution.LocalSessionChanges;

await xl.createWorkbook(workbookName, sheetName, conflictResolution);

Open

To open an Excel workbook, use the openWorkbook() method and pass as a required argument a file name or a path to the Excel file to open:

const fileName = "my-workbook.xlsx";

await xl.openWorkbook(fileName);

Save

To save an Excel workbook, use the saveAs() method and pass as required arguments a RangeInfo object and a name with which to save the Excel file:

const range = { workbook: "Book1" };
const fileName = "my-workbook.xlsx";

await xl.saveAs(range, fileName);

Tables

The following sections describe the available operations related to manipulating Excel tables.

Create

To create a table, use the createTable() method. Pass as required arguments a RangeInfo object, name for the table, style for the table, names for the columns, data for the columns, and a callback to be invoked when the table has been updated:

const range = { workbook: "Book1", worksheet: "Sheet1" };
const tableName = "My Table";
const tableStyle = "TableStyleDark1";
const columns = ["ID", "Name", "Email"];
const data = [
    ["1", "John Doe", "john@example.com"],
    ["2", "Jane Smith", "jane@example.com"]
];
const callback = origin => console.log(origin);

// Creating a named table with 3 named columns and 2 rows of data.
await xl.createTable(range, tableName, tableStyle, columns, data, callback);

Refresh

To refresh a table, use the refreshTable() method and pass as required arguments a RangeInfo object and the table name:

const range = { workbook: "Book1", worksheet: "Sheet1" };
const tableName = "My Table";

await xl.refreshTable(range, tableName);

Read Rows

To read table rows, use the readTableRows() method. Pass as required arguments a RangeInfo object, the table name, and the number of the row within the table from which to start the reading operation. Optionally, specify the number of table rows to read:

const range = { workbook: "Book1", worksheet: "Sheet1" };
const tableName = "My Table";
const fromRow = 1;
const rowsToRead = 10;

// Reading a specified number of rows from a table.
const { data } = await xl.readTableRows(range, tableName, fromRow, rowsToRead);

console.log(`Table columns data: ${JSON.stringify(data)}`);

Write Rows

To write table rows, use the writeTableRows() method. The rows will be inserted at the specified position. Pass as required arguments a RangeInfo object, the table name, the number of the row within the table where to insert the new rows, and a 2D array with the values for each cell of the rows:

const range = { workbook: "Book1", worksheet: "Sheet1" };
const tableName = "My Table";
const rowPosition = 1;
const values = [
    ["1", "John Doe", "john@example.com"]
];

// Writing (inserting) a single row at the specified position in the table.
await xl.writeTableRows(range, tableName, rowPosition, values);

Update Columns

To update table columns, use the updateTableColumns() method. Pass as required arguments a RangeInfo object, the table name, and an array of TableColumnOperationDescriptor objects describing the column operations:

const range = { workbook: "Book1", worksheet: "Sheet1" };
const tableName = "My Table";
const columnOperations = [
    {
        oldName: "Email",
        name: "Contact Details",
        op: "Rename"
    }
];

// Renaming a table column.
await xl.updateTableColumns(range, tableName, columnOperations);

Describe Columns

To retrieve details about table columns, use the describeTableColumns() method and pass as required arguments a RangeInfo object and the table name:

const range = { workbook: "Book1", worksheet: "Sheet1" };
const tableName = "My Table";

// Retrieving details about the table columns.
const { columns } = await xl.describeTableColumns(range, tableName);

Subscriptions

The following sections describe the available operations related to subscribing for updates from Excel.

Range Updates

To subscribe for range updates, use the subscribe() method and pass as required arguments a RangeInfo object and an XLCallback for handling the updates:

const range = { workbook: "Book1", worksheet: "Sheet1", range: "A1:C10" };
const callback = ({ intersect, address }) => console.log(`Updated cell address: ${address}, updated cell value: ${intersect}`);

await xl.subscribe(range, callback);

Destroy Subscription

To destroy an existing subscription, use the destroySubscription() method and pass as a required argument the subscription ID:

const range = { workbook: "Book1", worksheet: "Sheet1", range: "A1:C10" };
const callback = ({ intersect, address }) => console.log(`Updated cell address: ${address}, updated cell value: ${intersect}`);

// Creating a subscription.
const { subscriptionId } = await xl.subscribe(range, callback);

// Destroying an existing subscription.
const { message } = await xl.destroySubscription(subscriptionId);

console.log(message);

API Reference

The following API reference sections describe the data structures and the methods provided by the io.Connect Excel API.

Classes

IOConnectXLService

The IOConnectXLService is the entry point for the Excel Service API. Instantiate this class to initialize the Excel Service API.

Parameters:

Parameter Description
ioInstance Instance of the initialized @interopio/desktop library.

Methods:

Method Description
activate() Activates a range.
applyStyles() Applies styles to a range.
clearComments() Removes comments from a range.
clearContents() Removes the contents of a range.
createContextMenu() Creates a context menu associated with a range.
createContextMenuRaw() Raw version of createContextMenu() which accepts a SubscriptionInfo object instead of a subscription callback.
createDynamicRibbonMenu() Creates a dynamic ribbon menu. The created menu can be accessed from the "Dynamics" dropdown of the default Excel Adapter ribbon tab.
createDynamicRibbonMenuRaw() Raw version of createDynamicRibbonMenu() which accepts a SubscriptionInfo object instead of a subscription callback.
createOrUpdateCTP() Creates or updates an already existing custom task pane.
createOrUpdateCTPRaw() Raw version of createOrUpdateCTP() which accepts a SubscriptionInfo object instead of a subscription callback.
createTable() Creates a table with a specified range.
createWorkbook() Creates a new workbook with a specified sheet name.
describeTableColumns() Returns details describing the columns of a specified table and range.
destroyContextMenu() Destroys a specified context menu.
destroyContextMenuRaw() Raw version of destroyContextMenu().
destroyRibbonMenu() Destroys a specified dynamic ribbon menu.
destroyRibbonMenuRaw() Raw version of destroyRibbonMenu().
destroySubscription() Destroys a specified subscription.
openWorkbook() Opens an existing Excel workbook by a specified file name or a path to an Excel file.
read() Reads a specified range and returns the contents of each cell within the range.
readRef() Reads a specified range using an Excel reference notation (e.g., "Sheet1!A1:B5") and returns the contents of each cell within the range.
readTableRows() Reads a specified number of rows in a specified table and returns the contents of each row.
refreshTable() Refreshes a specified table.
saveAs() Saves an Excel workbook.
setRangeFormat() Formats a specified range.
subscribe() Subscribes for updates of cells within a specified range.
subscribeDeltas() Subscribes for updates of cells within a specified range and returns details about the cell update.
subscribeDeltasRaw() Raw version of subscribeDeltas() which accepts a SubscriptionInfo object instead of a subscription callback.
subscribeRaw() Raw version of subscribe() which accepts a SubscriptionInfo object instead of a subscription callback.
updateTableColumns() Updates the specified table columns.
write() Writes a specified value in each cell of a specified range.
writeComment() Writes a comment for each cell of a specified range.
writeRef() Writes a specified value in each cell of a range specified via an Excel reference notation (e.g., "Sheet1!A1:B5").
writeTableRows() Writes table rows from a specified row position within a specified table.

The following sections describe the methods provided by the IOConnectXLService class.

createTable()

Creates a table in an Excel workbook.

Signature:

createTable(
    range: RangeInfo,
    tableName: string,
    tableStyle: string,
    columns: string[],
    value: object[][],
    callback: XLCallback
): Promise<XLServiceResult>

Parameters:

Name Type Description
range object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
tableName string Required. Name for the table.
tableStyle string Required. Predefined Excel table style.
columns string[] Required. Array of names for the columns to create.
value object[][] Required. 2D array containing Excel values for the cells of each row in the table.
callback function Required. XLCallback to be invoked when the table has been updated.

Return value: XLServiceResult

createWorkbook()

Creates a new Excel workbook with a specified worksheet.

Signature:

createWorkbook(
    workbookFile: string,
    worksheet: string,
    saveConflictResolution: XLSaveConflictResolution = XLSaveConflictResolution.UserResolution
): Promise<XLServiceResult>

Parameters:

Name Type Description
workbookFile string Required. Name of the workbook to create.
worksheet string Required. Name of the worksheet to create in the new workbook.
saveConflictResolution string XLSaveConflictResolution value specifying how to handle save conflict resolutions. Defaults to XLSaveConflictResolution.UserResolution.

Return value: XLServiceResult

describeTableColumns()

Retrieves details about the columns of an Excel table.

Signature:

describeTableColumns(range: RangeInfo, tableName: string): Promise<XLServiceResult>

Parameters:

Name Type Description
range object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
tableName string Required. The name of the table whose columns to describe.

Return value: XLServiceResult

destroySubscription()

Destroys an existing subscription.

Signature:

destroySubscription(subscriptionId: string): Promise<XLServiceResult>

Parameters:

Name Type Description
subscriptionId string Required. The ID of the subscription to destroy. Can be extracted from the XLServiceResult returned by the subscription method.

Return value: XLServiceResult

openWorkbook()

Opens an existing Excel workbook file.

Signature:

openWorkbook(fileName: string): Promise<XLServiceResult>

Parameters:

Name Type Description
fileName string Required. File name or a path to an Excel file to open.

Return value: XLServiceResult

readTableRows()

Reads rows from an Excel table.

Signature:

readTableRows(
    range: RangeInfo,
    tableName: string,
    fromRow: number,
    rowsToRead?: number
): Promise<XLServiceResult>

Parameters:

Name Type Description
range object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
tableName string Required. The name of the table from which to read rows.
fromRow string Required. The position (1-based) of the row within the table from which to start the reading operation.
rowsToRead string The number of rows to read from the table.

Return value: XLServiceResult

refreshTable()

Refreshes an Excel table.

Signature:

refreshTable(range: RangeInfo, tableName: string): Promise<XLServiceResult>

Parameters:

Name Type Description
range object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
tableName string Required. The name of the table to refresh.

Return value: XLServiceResult

saveAs()

Saves an Excel workbook file.

Signature:

saveAs(range: RangeInfo, fileName: string): Promise<XLServiceResult>

Parameters:

Name Type Description
range object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
fileName string Required. File name under which to save the Excel file.

Return value: XLServiceResult

subscribe()

Subscribes for updates of an Excel range.

Signature:

subscribe(rangeInfo: RangeInfo, callback: XLCallback): Promise<XLServiceResult>

Parameters:

Name Type Description
rangeInfo object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
callback function Required. XLCallback to be invoked when the range has been updated.

updateTableColumns()

Updates columns in an Excel table.

Signature:

updateTableColumns(
    range: RangeInfo,
    tableName: string,
    columnOps: TableColumnOperationDescriptor[]
): Promise<XLServiceResult>

Parameters:

Name Type Description
range object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
tableName string Required. The name of the table in which to update columns.
columnOps object[] Required. Array of TableColumnOperationDescriptor objects describing the column operations to perform.

writeTableRows()

Writes (inserts) rows in an Excel table.

Signature:

writeTableRows(
    range: RangeInfo,
    tableName: string,
    rowPosition: number | null,
    value: object[][]
): Promise<XLServiceResult>

Parameters:

Name Type Description
range object Required. RangeInfo object describing the range associated with the operation and various settings to apply to that operation.
tableName string Required. The name of the table in which to write (insert) rows.
rowPosition number | null Required. The position (1-based) of the row within the table where to write (insert) the new rows. If not specified, the rows will be inserted after the last row in the table.
value object[][] Required. 2D array containing Excel values for the cells of each row.

Return value: XLServiceResult

Interfaces

CallbackInfo

Settings for the subscription callbacks attached to the custom task pane elements.

Properties:

Property Type Description
callbackApp string The name of an app (as specified in its definition) to target when invoking the Interop method specified in callbackEndpoint. All instances of the app will be targeted unless targetType is set to "Any".
callbackEndpoint string Required. Name of an Interop method to use as a callback for the subscription.
callbackId string Custom callback ID used as a cookie for tracking purposes.
callbackInstance string ID of an app instance to target when invoking the Interop method specified in callbackEndpoint.
targetType "All" | "Any" Determines the strategy for targeting Interop servers that have registered the Interop method specified in callbackEndpoint. Set to "All" to target all instances offering the Interop method specified in callbackEndpoint. Set to "Any" to target only the first instance that has registered this method. Defaults to "All".

RangeInfo

Describes an Excel range associated with the API operation to execute in Excel (e.g., read, write, subscribe, save, and more) and various settings to apply to that operation. This object is a required argument for most methods of the Excel Service API and is used for locating the Excel file on which to perform the API operation, as well as for providing settings for the operation itself. All properties are optional and if you set any properties that aren't relevant to the current API operation, they will be ignored.

Properties:

Property Type Description
expandRange boolean If true and there is data in any of the cells next to the outer cells of specified range, the range will be automatically expanded until it borders only with empty cells. Defaults to false.
forceCreate boolean If true, the specified workbook and worksheet will be created if they don't already exist. Defaults to false.
numberFormat string Number format to apply to the specified range.
range string Excel range (e.g., "A1:C10") associated with the operation.
resizeOrientation string DataOrientation value that determines the direction (horizontal or vertical) in which to expand any array data passed to the methods for executing writing operations in Excel.
workbook string Name of the Excel workbook associated with the operation.
worksheet string Name of the Excel worksheet associated with the operation.

SubscriptionInfo

Subscription settings when executing subscription operations (usually via raw methods such as subscribeRaw()).

Properties:

Property Type Description
callbackApp string The name of an app (as specified in its definition) to target when invoking the Interop method specified in callbackEndpoint. All instances of the app will be targeted unless targetType is set to "Any".
callbackEndpoint string Required. Name of an Interop method to use as a callback for the subscription.
callbackId string Custom callback ID used as a cookie for tracking purposes.
callbackInstance string ID of an app instance to target when invoking the Interop method specified in callbackEndpoint.
lifetime LifetimeType LifetimeType value that determines the length of the subscription - i.e., the conditions under which the Excel Adapter should stop sending subscription updates to the client. Defaults to LifetimeType.IOConnectInstance.
targetType "All" | "Any" Determines the strategy for targeting Interop servers that have registered the Interop method specified in callbackEndpoint. Set to "All" to target all instances offering the Interop method specified in callbackEndpoint. Set to "Any" to target only the first instance that has registered this method. Defaults to "All".

TableColumnInfo

Describes a table column.

Properties:

Property Type Description
address string Address of the table column (e.g., "$A$1:$A$3").
name string The name of the table column.

TableColumnOperationDescriptor

Describes a table column operation.

Properties:

Property Type Description
name string Name of the column on which to perform the operation. Required when renaming a column (used as a new name of the column). Required when position isn't specified when deleting or updating a column. If not specified when adding a column, defaults to "Column<consecutive-number>" (e.g., "Column1", "Column2", etc.).
oldName string The old name of the column when performing a renaming operation. Required for renaming operations if position isn't specified.
op string Required TableColumnOperation value that indicates the table column operation to perform.
position number | null The position (1-based) of the column on which to perform the operation. Required when renaming a column if oldName isn't specified. Required when deleting or updating a column if name isn't specified. If not specified when adding a column, the column will be added after the last table column.

XLServiceResult

Describes the result from executing an Excel Service API operation. Contains details about the result from executing the operation and additional details relevant to the specific API operation.

⚠️ Note that the XLServiceResult object will always contain all described properties, but only the ones relevant to the specific API operation will be populated. All other properties will be set to null.

The following tables describe all available XLServiceResult properties grouped by operation relevance.

Operation result properties:

Property Type Description
message string Message describing the operation result or error.
success boolean Flag indicating whether the operation is successful.

Common properties:

Property Type Description
address string Excel range address.
subscriptionId string The ID of the subscription when the operation is related to subscribing for updates from Excel.
workbook string The name of the Excel workbook.
worksheet string The name of the Excel worksheet.

Table operation properties:

Property Type Description
columns object[] Array of TableColumnInfo objects describing the table columns.
rowsCount number The number of table rows.
tableName string The name of the table.

Custom task pane operation properties:

Property Type Description
ctpHostId string The ID of the Excel element hosting the custom task pane.
ctpStore any The Excel storage mechanism related to the custom task pane.

Context and ribbon menu operation properties:

Property Type Description
caption string The caption of the Excel menu.
menuId string The Excel menu ID.
range object RangeInfo object describing the range associated with the Excel menu.
subscriptionInfo object SubscriptionInfo object describing the menu subscription settings (e.g., callback to invoke when the menu item is clicked).

File operation properties:

Property Type Description
fileName string The Excel file name when saving a workbook.

Window operation properties:

Property Type Description
activeWindow string The caption of the Excel window in which the range was activated. Populated only when you don't specify a workbook in which to activate the range.

Data operation properties:

Property Type Description
data any Data returned from reading operations (e.g., reading ranges, reading table rows).

Enums

LifetimeType

Enumeration of the possible values for determining the lifetime of the subscription - i.e., the conditions under which the Excel Adapter should stop sending subscription updates to the client:

Name Value Description
ExcelSession "ExcelSession" Reserved for future use.
Forever "Forever" Reserved for future use.
IOConnectInstance "GlueInstance" The Excel Adapter will send subscription updates to the client until its io.Connect API instance exists.
None "None" Reserved for future use.

XLSaveConflictResolution

Enumeration of the possible values for handling save conflict resolutions:

Name Value Description
LocalSessionChanges "xlLocalSessionChanges" Keep the local Excel session changes.
OtherSessionChanges "xlOtherSessionChanges" Keep the other Excel session changes.
UserResolution "xlUserResolution" Prompt the user to resolve the conflicts manually.

Types

DataOrientation

Determines the direction (horizontal or vertical) in which to expand any array data passed to the methods for executing writing operations in Excel.

Signature:

type DataOrientation = "Horizontal" | "Vertical";

TableColumnOperation

Indicates the table column operation to perform.

Signature:

type TableColumnOperation = "Add" | "Delete" | "Rename" | "Update";

XLCallback

Callback to be invoked when subscription updates are available.

Signature:

type XLCallback = (origin: any, ...props: any[]) => void;

Parameters:

Name Type Description
origin any Required. Object describing the subscription update.
props any[] Required. Any additional properties returned by the subscription update.

The origin parameter is an object whose shape varies depending on the particular subscription operation. It contains common properties valid for all subscription operations, as well as specific properties for some of the available subscription operations.

Common subscription properties:

Property Type Description
activeCell any The value of the active cell after an update.
activeCellAddress string The address of the active cell after an update (e.g., "$A$2").
callbackId string Custom callback ID used as a cookie for tracking purposes.
origin object | string Origin of the subscription update (e.g., the subscribe operation when subscribing to a range, the name of the updated table when subscribing to table updates, the object of the clicked custom Excel context menu).
selection any[] Mixed array of Excel values representing the values of the cells within the selection after an update.
selectionAddress string Address of the selection after an update (e.g, "$B$2:$B$3").
selectionCount number The number of the selected cells after an update.
subscriptionId string ID of the subscription operation.
workbook string The name of the workbook in which the subscription update has been triggered.
worksheet string The name of the workbook sheet in which the subscription update has been triggered.

Table subscription properties:

Property Type Description
range string The range address of the subscription update (e.g, "$B$2:$B$3").
table string The name of the updated Excel table.
value any The new value of the updated table cell. If more than one cells have been updated, this will be a mixed array of Excel table values.

Range subscription properties:

Property Type Description
address string The range address of the subscription update (e.g, "$B$2:$B$3").
intersect any The new value of the updated range cell. If more than one cells have been updated, this will be a mixed array of Excel table values.

Range delta subscription properties:

Property Type Description
deltas object[] Array of objects describing the updated Excel rows from the subscription range. Each object contains information about the type of the update (whether the row has been modified, deleted, or inserted), the row values after the update, the index of the row before and after the update, and the number of deleted rows when the update is row deletion.
subAddress string Range address of the subscription (e.g., "$A$1:$C$10").
updatedAddress string Range address of the update (e.g., "$A$2:$C$2").

Each object in the deltas array has the following properties:

Property Type Description
action "modified" | "deleted" | "inserted" The operation performed on the row.
count number The number of deleted rows when the update is row deletion. Defaults to -1 for all other operations.
row any[] | null Mixed array of Excel values representing the values of all cells of the updated row within the subscription range. If the row was deleted, this will be set to null.
rowBeforeIndex number The index of the row located before the updated row.

Custom task pane subscription properties:

Property Type Description
descriptor string The ID of the clicked element in the custom task pane.

Return value: void