Skip to content

XLSX API

XLSX APIs are called through the app returned by widget.render():

ts
const { widget } = await OfficeSdk.openfile({ docId: "demo-xlsx", fileName: "demo.xlsx", file });
const app = await widget.mount("#office-container").render();

Components

ComponentDescription
DocumentExport, zoom, editing state, and loading events
WorkbookWorksheets, palette, number formats, and protection state
WorksheetRows, columns, freeze panes, row height, and column width
SelectionCurrent selection content, font, borders, fill, alignment, and number format
FinderSearch, previous/next result, and search status
CursorCurrent mouse/cursor target area
UndoRedoUndo, redo, and availability state

Quick Example

ts
app.Document.setZoom(125);
app.Selection.setBold(true);
app.Selection.setFillColor({ r: 255, g: 242, b: 204 });
await app.Worksheet.insertRows();

app.Finder.search("revenue");
app.Finder.selectNext();

Event example:

ts
function onSelectionChange(info) {
  console.log(info);
}

app.Selection.addEventListener("SELECTION_CHANGE", onSelectionChange);

Document

MethodSignatureReturnsDescription
isEditing(): booleanbooleanWhether a cell is currently being edited.
setZoom(value: number, redraw?: boolean): booleanbooleanSets zoom percentage. redraw defaults to true; returns the underlying zoom operation result.
getZoom(): numbernumberGets zoom percentage.
focusEditor(): voidvoidCurrently a no-op in the XLSX implementation.
updateVisibleArea(): voidvoidRedraws the visible area of the current active worksheet.
exportDocument(): Promise<void>Promise<void>Exports the original workbook.
exportPdf(printOptions?: unknown): Promise<void>Promise<void>Exports PDF with print options.
copy(): Promise<void>Promise<void>Copies the current selection.
cut(): Promise<void>Promise<void>Cuts the current selection.
paste(): Promise<void>Promise<void>Pastes into the current selection.
startReadOnly(): voidvoidEnters read-only state.
endReadOnly(): voidvoidExits read-only state.
isReadOnly(): booleanbooleanGets the current read-only state.

Example:

ts
if (!app.Document.isEditing()) {
  app.Document.setZoom(110);
}

await app.Document.exportDocument();
await app.Document.exportPdf();

Document component events:

Event NamePayloadDescription
XLSX_WORKSHEET_LOADEDNoneWorksheet loaded.
XLSX_END_LOADINGNoneDocument loading completed.
DOCUMENT_EXPORT_READYNoneExport completed.
DOCUMENT_EDITING_ENABLEDNoneThe document entered editable state.
DOCUMENT_EDITING_DISABLEDNoneThe document exited editable state.
XLSX_EDITING_STATUS_CHANGE(status: boolean)Cell editing state changed.
XLSX_ZOOM_CHANGENoneZoom changed.
XLSX_WORKSHEET_LOADING_RATIO(ratio: number)Worksheet loading progress.
XLSX_FIRST_PART_LOADINGNoneFirst batch content loaded.
XLSX_WORKSHEET_CHANGE({ sheetProtected?: boolean })Current worksheet changed.

exportPdf(...) requires a secure context (normally HTTPS or localhost), window.queryLocalFonts, and permission to access local fonts. If these requirements are not met, the current implementation does not perform the PDF export.

Workbook

MethodSignatureReturnsDescription
addWorksheet(): voidvoidAdds a worksheet.
setWorksheetName(name: string, index?: number): boolean | numberboolean | numberSets worksheet name. If index is omitted, the active worksheet is used. Returns success or a name-validation status code.
deleteWorksheet(index?: number): voidvoidDeletes a worksheet. If index is omitted, the active worksheet is deleted.
getWorksheetName(index?: number): stringstringGets worksheet name. If index is omitted, the active worksheet is read.
getColorPalette(): { theme: unknown[]; standard: unknown[] }{ theme; standard }Gets the color palette.
getCellNumberFormats(): string[]string[]Gets number format category list.
getNumberFormatExample(format: string, value?: unknown, lcid?: unknown): unknownunknownGets a number format example.
getNumberFormatExamples(formats: string[], value?: unknown, lcid?: unknown): unknownunknownGets number format examples in batch.
isWorksheetProtected(index?: number): booleanbooleanChecks whether a worksheet is protected. If index is omitted, the active worksheet is checked.

Example:

ts
app.Workbook.addWorksheet();
app.Workbook.setWorksheetName("Summary");

const name = app.Workbook.getWorksheetName();
const protectedSheet = app.Workbook.isWorksheetProtected();

const formats = app.Workbook.getCellNumberFormats();
const examples = app.Workbook.getNumberFormatExamples(["0.00", "0%"], 1234.56, "en-US");

Worksheet

MethodSignatureReturnsDescription
isFrozenPane(): booleanbooleanWhether panes are currently frozen.
toggleFreezePanes(): voidvoidToggles freeze/unfreeze panes.
setRowHeight(heightPt: number): Promise<unknown>Promise<unknown>Sets current row height. Empty values are ignored.
insertRows(): Promise<unknown>Promise<unknown>Inserts rows.
hideRows(): Promise<unknown>Promise<unknown>Hides rows.
unhideRows(): Promise<unknown>Promise<unknown>Unhides rows.
deleteRows(): Promise<unknown>Promise<unknown>Deletes rows.
insertColumns(): Promise<unknown>Promise<unknown>Inserts columns.
setColumnWidth(nChars: number): voidvoidSets current column width in character width units. Empty values are ignored.
hideColumns(): Promise<unknown>Promise<unknown>Hides columns.
unhideColumns(): Promise<unknown>Promise<unknown>Unhides columns.
deleteColumns(): Promise<unknown>Promise<unknown>Deletes columns.
getRowHeight(row?: number | null, wsIdx?: number | null): numbernumberGets row height. If omitted or null, the current context is used.
getColumnWidth(col?: number | null, wsIdx?: number | null): numbernumberGets column width. If omitted or null, the current context is used.

Example:

ts
if (!app.Worksheet.isFrozenPane()) {
  app.Worksheet.toggleFreezePanes();
}

await app.Worksheet.setRowHeight(24);
app.Worksheet.setColumnWidth(12);

const rowHeight = app.Worksheet.getRowHeight();
const colWidth = app.Worksheet.getColumnWidth();

Selection

Selection methods operate on the current active cell or selection.

MethodSignatureReturnsDescription
clearContents(): voidvoidClears content in the current selection.
setAccountingFormat(value: AccountingFormat): Promise<unknown> | falsePromise<unknown> | falseSets accounting format. Returns false for invalid format values.
setUnderline(value: string): voidvoidSets underline.
setBorder(value: BorderValue): voidvoidSets borders.
setStrikeThrough(value: boolean): voidvoidSets strikethrough.
setBold(value: boolean): voidvoidSets bold.
setItalic(value: boolean): voidvoidSets italic.
setFontSize(value: string | number): voidvoidSets font size. Must satisfy 0 < value <= 409.
setHorizontalAlignment(value: string): voidvoidSets horizontal alignment.
setVerticalAlignment(value: string | number): voidvoidSets vertical alignment. Prefer string values.
setFontColor(value: XlsxColor): voidvoidSets font color.
setFillColor(value: XlsxColor): voidvoidSets fill color.
setFontName(value: string): voidvoidSets font family.
setCellStyle(value: string): Promise<unknown>Promise<unknown>Sets cell style.
setPercentFormat(): Promise<unknown>Promise<unknown>Sets percent format.
setNumberFormat(value: unknown): Promise<unknown>Promise<unknown>Sets number format.
increaseDecimalPlaces(): voidvoidIncreases decimal places.
decreaseDecimalPlaces(): voidvoidDecreases decimal places.
ts
type AccountingFormat = "RMB" | "Dollar" | "EUR" | "GBP" | "JPY" | "none";

type XlsxColor =
  | { r: number; g: number; b: number }
  | { theme: number; tint?: number }
  | { indexed: number }
  | { rgbHex: string };

type BorderValue = {
  color: XlsxColor;
  position: string;
  style: string;
};

rgbHex supports 6-digit RRGGBB or 8-digit AARRGGBB. The 8-digit form can carry alpha; the { r, g, b } RGB object itself does not support transparency.

While cell text is being edited, setBold, setItalic, setUnderline, and setStrikeThrough toggle the current state and ignore the supplied boolean value. setHorizontalAlignment and setVerticalAlignment currently have no effect in that editing state.

Common enums:

ParameterCommon Values
setUnderline(value)"single", "none"
setHorizontalAlignment(value)"left", "center", "right", "justify", "distributed"
setVerticalAlignment(value)"top", "center", "bottom", "justify", "distributed"; runtime numeric values are accepted for compatibility
setAccountingFormat(value)"RMB", "Dollar", "EUR", "GBP", "JPY", "none"
BorderValue.position"all", "none", "inner", "outer", "left", "right", "top", "bottom", "verticalInner", "horizontalInner", "diagonalUp", "diagonalDown"
BorderValue.style"hair", "dotted", "dashed", "thin", "medium", "thick", "double", "dashDot", "dashDotDot", "mediumDashed", "mediumDashDot", "mediumDashDotDot", "slantDashDot"; when clearing borders, use position: "none"

Example:

ts
app.Selection.clearContents();

app.Selection.setFontName("Arial");
app.Selection.setFontSize(12);
app.Selection.setBold(true);
await app.Selection.setAccountingFormat("RMB");
app.Selection.setFontColor({ r: 192, g: 0, b: 0 });
app.Selection.setFillColor({ r: 255, g: 242, b: 204 });

app.Selection.setBorder({
  color: { r: 0, g: 0, b: 0 },
  position: "all",
  style: "thin"
});

await app.Selection.setNumberFormat("0.00");
app.Selection.increaseDecimalPlaces();

Selection component events:

Event NamePayload
SELECTION_CHANGEXlsxSelectionChange or the raw event object
ts
type XlsxSelectionChange = {
  bold: boolean;
  italic: boolean;
  fontName: string;
  fontSize: number | string;
  fontColor: unknown;
  underline: string;
  strikeout: boolean;
  fillColor: unknown;
  alignHorizontal: string;
  alignVertical: string;
  numFormat: string;
  numFormatType: string;
  canCopy?: boolean;
  bSelectAll?: boolean;
  isText?: boolean;
};

Finder

MethodSignatureReturnsDescription
search(text: string, callback?: (...args: unknown[]) => void): voidvoidStarts searching for a keyword. Optional callback supported.
selectFirst(): voidvoidMoves to the first search result.
selectNext(): voidvoidMoves to the next search result.
selectPrevious(): voidvoidMoves to the previous search result.
getSearchStatus(): unknownunknownGets search status.

Finder component events:

Event NamePayloadDescription
XLSX_OPEN_FIND_UINoneThe document requests opening the find UI.

Example:

ts
app.Finder.search("Q1");
app.Finder.selectFirst();
app.Finder.selectNext();

console.log(app.Finder.getSearchStatus());

Cursor

MethodSignatureReturnsDescription
getTargetType(): "" | "columnHeader" | "rowHeader" | "cells" | "navBar"stringGets the current mouse/cursor target area.

Return values:

ValueDescription
""No stable target currently.
"cells"Cell area.
"rowHeader"Row header.
"columnHeader"Column header.
"navBar"Bottom worksheet tab area.

Example:

ts
const targetType = app.Cursor.getTargetType();
if (targetType === "cells") {
  app.Selection.setBold(true);
}

UndoRedo

MethodSignatureReturnsDescription
undo(callback?: (value: unknown) => void): voidvoidUndo. Optional callback supported.
redo(callback?: (value: unknown) => void): voidvoidRedo. Optional callback supported.
canUndo(): booleanbooleanWhether undo is available.
canRedo(): booleanbooleanWhether redo is available.

UndoRedo component events:

Event NamePayload
UNDO_REDO_STATE_CHANGENone

Example:

ts
if (app.UndoRedo.canRedo()) {
  app.UndoRedo.redo();
}