Skip to Content
ClassesFUniver

Class: FUniver

The root Facade API object to interact with Univer. Please use newAPI static method to create a new instance.

Extends

  • IFUniverNetworkMixin.IFUniverNetworkMixin.IFUniverEngineFormulaMixin.IFUniverSheetsMixin.IFUniverSheetsFormulaMixin.IFUnvierDataValidationMixin.IFUniverCommentMixin.IFUniverCollaborationClientMixin.IFUniverPivotTableEventMixin.IFUniverDocsUIMixin.IFUniverUIMixin.IFUniverSheetsUIMixin.IFUniverFindReplaceMixin.IFUniverCrosshairHighlightMixin.IFUniverWatermarkMixin.IFUniverSheetsZenEditorMixin.IFUniverNodeRuntimeMixin.IFUniverExchangeClientMixin

Properties

PropertyModifierTypeDescription

CROSSHAIR_HIGHLIGHT_COLORS

readonly

string[]

Get the available built-in colors for the crosshair highlight.

Accessors

Enum

Get Signature

get Enum(): FEnum
Returns

FEnum


Event

Get Signature

get Event(): FEventName
Returns

FEventName


Util

Get Signature

get Util(): FUtil
Returns

FUtil

Methods

addEvent()

addEvent<T>(event, callback): IDisposable

Add an event listener

Type Parameters

Type Parameter
T extends keyof IEventParamConfig

Parameters

ParameterTypeDescription
eventTkey of event
callback(params) => voidcallback when event triggered

Returns

IDisposable

The Disposable instance, for remove the listener

Example

// Add life cycle changed event listener const disposable = univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, (params) => { const { stage } = params; console.log('life cycle changed', params); }); // Remove the event listener, use `disposable.dispose()`

addWatermark()

Call Signature

addWatermark(type, config): FUniver

Adds a watermark to the unit. Supports both text and image watermarks based on the specified type.

Parameters
ParameterTypeDescription
typeTextThe type of watermark to add is Text.
configITextWatermarkConfigThe configuration object for the text type watermark.
Returns

FUniver

The FUniver instance for chaining.

Throws

Throws an error if the watermark type is unknown.

Example
univerAPI.addWatermark('text', { content: 'Univer', fontSize: 20, repeat: true, });

Call Signature

addWatermark(type, config): FUniver

Adds a watermark to the unit. Supports both text and image watermarks based on the specified type.

Parameters
ParameterTypeDescription
typeImageThe type of watermark to add is Image.
configIImageWatermarkConfigThe configuration object for the image type watermark.
Returns

FUniver

The FUniver instance for chaining.

Throws

Throws an error if the watermark type is unknown.

Example
univerAPI.addWatermark('image', { url: 'https://avatars.githubusercontent.com/u/61444807?s=48&v=4', width: 100, height: 100, });

Call Signature

addWatermark(type, config): FUniver
Parameters
ParameterType
typeany
configany
Returns

FUniver


copy()

copy(): Promise<boolean>

Copy the current selected content of the currently focused unit into your system clipboard.

Returns

Promise<boolean>

whether the copy operation is successful

Example

// Prevent failure due to loss of focus when executing copy and paste code in the console, // this example listens for the cell click event and executes the copy and paste code. univerAPI.addEvent(univerAPI.Event.CellClicked, async (params) => { const fWorkbook = univerAPI.getActiveWorkbook(); const fWorksheet = fWorkbook.getActiveSheet(); // Copy the range A1:B2 to the clipboard const fRange = fWorksheet.getRange('A1:B2'); fRange.activate().setValues([ [1, 2], [3, 4] ]); await univerAPI.copy(); // Paste the copied content to the range C1:D2 const fRange2 = fWorksheet.getRange('C1'); fRange2.activate(); await univerAPI.paste(); // Check the pasted content console.log(fWorksheet.getRange('C1:D2').getValues()); // [[1, 2], [3, 4]] });

createMenu()

createMenu(menuItem): FMenu

Create a menu build object. You can insert new menus into the UI.

Parameters

ParameterTypeDescription
menuItemIFacadeMenuItemthe menu item

Returns

FMenu

the FMenu object

Example

// Univer Icon can be viewed at https://univer.ai/en-US/icons import { SmileSingle } from '@univerjs/icons' // Create a custom menu with an univer icon univerAPI.registerComponent('custom-menu-icon', SmileSingle); univerAPI.createMenu({ id: 'custom-menu', icon: 'custom-menu-icon', title: 'Custom Menu', tooltip: 'Custom Menu Tooltip', action: () => { console.log('Custom Menu Clicked'); }, }).appendTo('ribbon.start.others'); // Or // Create a custom menu with an image icon univerAPI.registerComponent('custom-menu-icon', () => { return <img src="https://avatars.githubusercontent.com/u/61444807?s=48&v=4" alt="" style={{ width: '16px', height: '16px' }} />; }); univerAPI.createMenu({ id: 'custom-menu', icon: 'custom-menu-icon', title: 'Custom Menu', tooltip: 'Custom Menu Tooltip', action: () => { console.log('Custom Menu Clicked'); }, }).appendTo('ribbon.start.others'); // Or // Create a custom menu without an icon univerAPI.createMenu({ id: 'custom-menu', title: 'Custom Menu', tooltip: 'Custom Menu Tooltip', action: () => { console.log('Custom Menu Clicked'); }, }).appendTo('ribbon.start.others');

createSubmenu()

createSubmenu(submenuItem): FSubmenu

Create a menu that contains submenus, and later you can append this menu and its submenus to the UI.

Parameters

ParameterTypeDescription
submenuItemIFacadeSubmenuItemthe submenu item

Returns

FSubmenu

the FSubmenu object

Example

// Create two leaf menus. const menu1 = univerAPI.createMenu({ id: 'submenu-nested-1', title: 'Item 1', action: () => { console.log('Item 1 clicked'); } }); const menu2 = univerAPI.createMenu({ id: 'submenu-nested-2', title: 'Item 2', action: () => { console.log('Item 2 clicked'); } }); // Add the leaf menus to a submenu. const submenu = univerAPI.createSubmenu({ id: 'submenu-nested', title: 'Nested Submenu' }) .addSubmenu(menu1) .addSeparator() .addSubmenu(menu2); // Create a root submenu append to the `contextMenu.others` section. univerAPI.createSubmenu({ id: 'custom-submenu', title: 'Custom Submenu' }) .addSubmenu(submenu) .appendTo('contextMenu.others');

createTextFinderAsync()

createTextFinderAsync(text): Promise<FTextFinder>

Create a text-finder for the current univer.

Parameters

ParameterTypeDescription
textstringThe text to find.

Returns

Promise<FTextFinder>

A promise that resolves to the text-finder instance.

Example

// Assume the current sheet is empty sheet. const fWorkbook = univerAPI.getActiveWorkbook(); const fWorksheet = fWorkbook.getActiveSheet(); const fRange = fWorksheet.getRange('A1:D10'); fRange.setValues([ [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13] ]); // Create a text-finder to find the text '5'. const textFinder = await univerAPI.createTextFinderAsync('5'); // Find all cells that contain the text '5'. const matchCells = textFinder.findAll(); matchCells.forEach((cell) => { console.log(cell.getA1Notation()); // D2, C3, B4, A5 });

createUniverDoc()

createUniverDoc(data): FDocument

Create a new document and get the API handler of that document.

Parameters

ParameterTypeDescription
dataPartial<IDocumentData>The snapshot of the document.

Returns

FDocument

FDocument API instance.


createUniverSheet()

createUniverSheet(data): FWorkbook

Parameters

ParameterType
dataPartial<IWorkbookData>

Returns

FWorkbook

Deprecated

use univerAPI.createWorkbook instead.


createWorkbook()

createWorkbook(data, options?): FWorkbook

Create a new spreadsheet and get the API handler of that spreadsheet.

Parameters

ParameterTypeDescription
dataPartial<IWorkbookData>The snapshot of the spreadsheet.
options?ICreateUnitOptionsThe options of creating the spreadsheet.

Returns

FWorkbook

FWorkbook API instance.

Example

const fWorkbook = univerAPI.createWorkbook({ id: 'Sheet1', name: 'Sheet1' }); console.log(fWorkbook);

Add you can make the workbook not as the active workbook by setting options:

const fWorkbook = univerAPI.createWorkbook({ id: 'Sheet1', name: 'Sheet1' }, { makeCurrent: false }); console.log(fWorkbook);

customizeColumnHeader()

customizeColumnHeader(cfg): void

Parameters

ParameterTypeDescription
cfgIColumnsHeaderCfgParamThe configuration of the column header.

Returns

void

Deprecated

use same API in FWorkSheet. Customize the column header of the spreadsheet.

Example

univerAPI.customizeColumnHeader({ headerStyle: { fontColor: '#fff', size: 40, backgroundColor: '#4e69ee', fontSize: 9 }, columnsCfg: ['MokaII', undefined, null, { text: 'Size', textAlign: 'left' }] });

customizeRowHeader()

customizeRowHeader(cfg): void

Parameters

ParameterTypeDescription
cfgIRowsHeaderCfgParamThe configuration of the row header.

Returns

void

Deprecated

use same API in FWorkSheet. Customize the row header of the spreadsheet.

Example

univerAPI.customizeRowHeader({ headerStyle: { backgroundColor: 'pink', fontSize: 9 }, rowsCfg: ['MokaII', undefined, null, { text: 'Size', textAlign: 'left' }] });

deleteWatermark()

deleteWatermark(): FUniver

Deletes the currently applied watermark from the unit. This function retrieves the watermark service and invokes the method to remove any existing watermark configuration.

Returns

FUniver

The FUniver instance for chaining.

Example

univerAPI.deleteWatermark();

disposeUnit()

disposeUnit(unitId): boolean

Dispose the UniverSheet by the unitId. The UniverSheet would be unload from the application.

Parameters

ParameterTypeDescription
unitIdstringThe unit id of the UniverSheet.

Returns

boolean

Whether the Univer instance is disposed successfully.

Example

const fWorkbook = univerAPI.getActiveWorkbook(); const unitId = fWorkbook?.getId(); if (unitId) { univerAPI.disposeUnit(unitId); }

executeCommand()

executeCommand<P, R>( id, params?, options?): Promise<R>

Execute a command with the given id and parameters.

Type Parameters

Type ParameterDefault type
P extends objectobject
Rboolean

Parameters

ParameterTypeDescription
idstringIdentifier of the command.
params?PParameters of this execution.
options?IExecutionOptionsOptions of this execution.

Returns

Promise<R>

The result of the execution. It is a boolean value by default which indicates the command is executed.

Example

univerAPI.executeCommand('sheet.command.set-range-values', { value: { v: "Hello, Univer!" }, range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } });

exportXLSXBySnapshot()

exportXLSXBySnapshot(snapshot): Promise<File>

Export XLSX file by workbook data

Parameters

ParameterTypeDescription
snapshotIWorkbookDataWorkbook data

Returns

Promise<File>

XLSX file

Deprecated

Please use exportXLSXBySnapshotAsync instead.


exportXLSXBySnapshotAsync()

exportXLSXBySnapshotAsync(snapshot): Promise<File>

Export XLSX file by workbook data

Parameters

ParameterTypeDescription
snapshotIWorkbookDataWorkbook data

Returns

Promise<File>

A promise that resolves to the XLSX file

Example

const fWorkbook = univerAPI.getActiveWorkbook(); const snapshot = fWorkbook.save(); const file = await univerAPI.exportXLSXBySnapshotAsync(snapshot); // Download the file const url = URL.createObjectURL(file); const a = document.createElement('a'); a.href = url; a.download = 'filename.xlsx'; a.click(); URL.revokeObjectURL(url);

exportXLSXByUnitId()

exportXLSXByUnitId(unitId): Promise<File>

Export XLSX file by unit id

Parameters

ParameterTypeDescription
unitIdstringUnit id

Returns

Promise<File>

XLSX file

Deprecated

Please use exportXLSXByUnitIdAsync instead.


exportXLSXByUnitIdAsync()

exportXLSXByUnitIdAsync(unitId): Promise<File>

Export XLSX file by unit id

Parameters

ParameterTypeDescription
unitIdstringUnit id

Returns

Promise<File>

A promise that resolves to the XLSX file

Example

const fWorkbook = univerAPI.getActiveWorkbook(); const unitId = fWorkbook.getId(); const file = await univerAPI.exportXLSXByUnitIdAsync(unitId); // Download the file const url = URL.createObjectURL(file); const a = document.createElement('a'); a.href = url; a.download = 'filename.xlsx'; a.click(); URL.revokeObjectURL(url);

generatePivotTable()

generatePivotTable<T>(data, CustomDataFieldManager?): FGenericPivotTable

Create a pivot table instance that does not depend on a workbook

Type Parameters

Type Parameter
T extends DataFieldManager

Parameters

ParameterTypeDescription
data[…[], ...(...)[][]]The data used to create the pivot table
CustomDataFieldManager?(…args) => TThe custom data field manager class. If not passed, the default DataFieldManager will be used

Returns

FGenericPivotTable

The generated pivot table instance.

Example

const sourceData = [ ["区域", "省份", "城市", "类别", "商品", "数量", "销售日期"], ["西部", "河南", "洛阳", "fruit", "葡萄", 38, "2021-06-30"], ["北部", "辽宁", "沈阳", "fruit", "葡萄", 45, "2023-08-31"] ] const pivot = univerAPI.generatePivotTable(sourceData); pivot.addFieldWithName('数量', 3); const res = pivot.getResultByCalculate(); console.log('debugger', pivot, res);

getActiveDocument()

getActiveDocument(): FDocument

Get the currently focused Univer document.

Returns

FDocument

The currently focused Univer document.


getActiveSheet()

getActiveSheet(): Nullable<{ workbook: ...; worksheet: ...; }>

Get the active sheet.

Returns

Nullable<{ workbook: …; worksheet: …; }>

The active sheet.

Example

const target = univerAPI.getActiveSheet(); if (!target) return; const { workbook, worksheet } = target; console.log(workbook, worksheet);

getActiveUniverSheet()

getActiveUniverSheet(): FWorkbook

Returns

FWorkbook

Deprecated

use univerAPI.getActiveWorkbook instead


getActiveWorkbook()

getActiveWorkbook(): FWorkbook

Get the currently focused Univer spreadsheet.

Returns

FWorkbook

The currently focused Univer spreadsheet.

Example

const fWorkbook = univerAPI.getActiveWorkbook(); console.log(fWorkbook);

getCollaboration()

getCollaboration(): FCollaboration

Get the collaboration instance to manage the collaboration issue of the current univer.

Returns

FCollaboration

The collaboration instance.

Example

const collaboration = univerAPI.getCollaboration();

getCommandSheetTarget()

getCommandSheetTarget(commandInfo): Nullable<{ workbook: ...; worksheet: ...; }>

Get the target of the sheet.

Parameters

ParameterTypeDescription
commandInfoICommandInfo<object>The commandInfo of the command.

Returns

Nullable<{ workbook: …; worksheet: …; }>

  • The target of the sheet.

Example

univerAPI.addEvent(univerAPI.Event.CommandExecuted, (commandInfo) => { const target = univerAPI.getCommandSheetTarget(commandInfo); if (!target) return; const { workbook, worksheet } = target; console.log(workbook, worksheet); });

getComponentManager()

getComponentManager(): ComponentManager

Get the component manager

Returns

ComponentManager

The component manager

Example

const componentManager = univerAPI.getComponentManager(); console.log(componentManager);

getCrosshairHighlightColor()

getCrosshairHighlightColor(): string

Get the color of the crosshair highlight.

Returns

string

The color of the crosshair highlight

Example

console.log(univerAPI.getCrosshairHighlightColor());

getCrosshairHighlightEnabled()

getCrosshairHighlightEnabled(): boolean

Get whether the crosshair highlight is enabled.

Returns

boolean

Whether the crosshair highlight is enabled

Example

console.log(univerAPI.getCrosshairHighlightEnabled());

getCurrentLifecycleStage()

getCurrentLifecycleStage(): LifecycleStages

Get the current lifecycle stage.

Returns

LifecycleStages

  • The current lifecycle stage.

Example

const stage = univerAPI.getCurrentLifecycleStage(); console.log(stage);

getFormula()

getFormula(): FFormula

Returns

FFormula


getHooks()

getHooks(): FHooks

Get hooks.

Returns

FHooks

FHooks instance

Deprecated

use addEvent instead.


getPermission()

getPermission(): FPermission

Get the PermissionInstance.

Returns

FPermission

Deprecated

This function is deprecated and will be removed in version 0.6.0. Please use the function with the same name on the FWorkbook instance instead.


getSheetHooks()

getSheetHooks(): FSheetHooks

Returns

FSheetHooks

Deprecated

use univerAPI.addEvent as instead.


getSheetTarget()

getSheetTarget(unitId, subUnitId): Nullable<{ workbook: ...; worksheet: ...; }>

Get the target of the sheet.

Parameters

ParameterTypeDescription
unitIdstringThe unitId of the sheet.
subUnitIdstringThe subUnitId of the sheet.

Returns

Nullable<{ workbook: …; worksheet: …; }>

  • The target of the sheet.

Example

const unitId = 'workbook-01'; const subUnitId = 'sheet-0001'; const target = univerAPI.getSheetTarget(unitId, subUnitId); if (!target) return; const { workbook, worksheet } = target; console.log(workbook, worksheet);

getShortcut()

getShortcut(): FShortcut

Get the Shortcut handler to interact with Univer’s shortcut functionalities.

Returns

FShortcut

the FShortcut object

Example

const fShortcut = univerAPI.getShortcut(); // Disable shortcuts of Univer fShortcut.disableShortcut(); // Enable shortcuts of Univer fShortcut.enableShortcut(); // Trigger a shortcut const fWorkbook = univerAPI.getActiveWorkbook(); const fWorksheet = fWorkbook.getActiveSheet(); const fRange = fWorksheet.getRange('A1'); fRange.activate(); fRange.setValue('Hello Univer'); console.log(fRange.getCellStyle().bold); // false const pseudoEvent = new KeyboardEvent('keydown', { key: 'b', ctrlKey: true, keyCode: univerAPI.Enum.KeyCode.B }); const ifShortcutItem = fShortcut.triggerShortcut(pseudoEvent); if (ifShortcutItem) { const commandId = ifShortcutItem.id; console.log(fRange.getCellStyle().bold); // true }

getUniverDoc()

getUniverDoc(id): FDocument

Get the document API handler by the document id.

Parameters

ParameterTypeDescription
idstringThe document id.

Returns

FDocument

The document API instance.


getUniverSheet()

getUniverSheet(id): FWorkbook

Get the spreadsheet API handler by the spreadsheet id.

Parameters

ParameterTypeDescription
idstringThe spreadsheet id.

Returns

FWorkbook

The spreadsheet API instance.

Example

const fWorkbook = univerAPI.getUniverSheet('Sheet1'); console.log(fWorkbook); const fWorkbook = univerAPI.getWorkbook('Sheet1'); console.log(fWorkbook);

getURL()

getURL(): URL

Return the URL of the current page.

Returns

URL

the URL object

Example

console.log(univerAPI.getURL());

getUserManager()

getUserManager(): FUserManager

Returns

FUserManager


getWorkbook()

getWorkbook(id): FWorkbook

Parameters

ParameterType
idstring

Returns

FWorkbook


importDOCXToSnapshot()

importDOCXToSnapshot(file): Promise<IDocumentData>

Import DOCX file to document data

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<IDocumentData>

Document data

Deprecated

Please use importDOCXToSnapshotAsync instead.


importDOCXToSnapshotAsync()

importDOCXToSnapshotAsync(file): Promise<IDocumentData>

Import DOCX file to document data

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<IDocumentData>

A promise that resolves to the document data

Example

// Accepts a File object const snapshot = await univerAPI.importDOCXToSnapshotAsync(file); // Or accepts a URL to a remote file // const snapshot = await univerAPI.importDOCXToSnapshotAsync('https://example.com/filename.docx'); console.log('Snapshot created:', snapshot);

importDOCXToUnitId()

importDOCXToUnitId(file): Promise<string>

Import DOCX file to unit id

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<string>

Unit id

Deprecated

Please use importDOCXToUnitIdAsync instead.


importDOCXToUnitIdAsync()

importDOCXToUnitIdAsync(file): Promise<string>

Import DOCX file to unit id

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<string>

A promise that resolves to the unit id

Example

// Accepts a File object const unitId = await univerAPI.importDOCXToUnitIdAsync(file); // Or accepts a URL to a remote file // const unitId = await univerAPI.importDOCXToUnitIdAsync('https://example.com/filename.docx'); const url = new URL(window.location.href); const unit = url.searchParams.get('unit'); url.searchParams.set('unit', unitId); url.searchParams.set('type', "1"); // The meaning of "1" is String(UniverInstanceType.UNIVER_DOC) // Open the unit in the new window window.open(url.toString(), '_blank');

importXLSXToSnapshot()

importXLSXToSnapshot(file): Promise<IWorkbookData>

Import XLSX file to workbook data

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<IWorkbookData>

Workbook data

Deprecated

Please use importXLSXToSnapshotAsync instead.


importXLSXToSnapshotAsync()

importXLSXToSnapshotAsync(file): Promise<IWorkbookData>

Import XLSX file to workbook data

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<IWorkbookData>

A promise that resolves to the workbook data

Example

// Accepts a File object const snapshot = await univerAPI.importXLSXToSnapshotAsync(file); // Or accepts a URL to a remote file // const snapshot = await univerAPI.importXLSXToSnapshotAsync('https://example.com/filename.xlsx'); console.log('Snapshot created:', snapshot); // see more: https://docs.univer.ai/en-US/guides/sheets/getting-started/workbook-data // Create a new workbook with the snapshot univerAPI.createWorkbook(snapshot);

importXLSXToUnitId()

importXLSXToUnitId(file): Promise<string>

Import XLSX file to unit id

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<string>

Unit id

Deprecated

Please use importXLSXToUnitIdAsync instead.


importXLSXToUnitIdAsync()

importXLSXToUnitIdAsync(file): Promise<string>

Import XLSX file to unit id

Parameters

ParameterTypeDescription
filestring | FileFile path or file object

Returns

Promise<string>

A promise that resolves to the unit id

Example

// Accepts a File object const unitId = await univerAPI.importXLSXToUnitIdAsync(file); // Or accepts a URL to a remote file // const unitId = await univerAPI.importXLSXToUnitIdAsync('https://example.com/filename.xlsx'); // Utilize automatic data loading in conjunction with collaborative editing. https://docs.univer.ai/en-US/guides/sheets/features/collaboration#loading-collaborative-documents const url = new URL(window.location.href); const unit = url.searchParams.get('unit'); url.searchParams.set('unit', unitId); url.searchParams.set('type', "2"); // The meaning of "2" is String(UniverInstanceType.UNIVER_SHEET) console.log('Unit URL:', url.toString()); // Open the unit in the new window window.open(url.toString(), '_blank');

isUIVisible()

isUIVisible(key): boolean

Get the visibility of a built-in UI part.

Parameters

ParameterTypeDescription
keyBuiltInUIPartthe built-in UI part

Returns

boolean

the visibility

Example

// Hide header univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false); console.log(univerAPI.isUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER)); // false

newBlob()

newBlob(): FBlob

Create a new blob.

Returns

FBlob

The new blob instance

Example

const blob = univerAPI.newBlob();

newColor()

newColor(): ColorBuilder

Create a new color.

Returns

ColorBuilder

The new color instance

Example

const color = univerAPI.newColor();

newDataValidation()

newDataValidation(): FDataValidationBuilder

Creates a new instance of FDataValidationBuilder

Returns

FDataValidationBuilder

A new instance of the FDataValidationBuilder class

Example

const fWorkbook = univerAPI.getActiveWorkbook(); const fWorksheet = fWorkbook.getActiveSheet(); // Create a new data validation rule that requires a number between 1 and 10 fot the range A1:B10 const fRange = fWorksheet.getRange('A1:B10'); const rule = univerAPI.newDataValidation() .requireNumberBetween(1, 10) .setOptions({ allowBlank: true, showErrorMessage: true, error: 'Please enter a number between 1 and 10' }) .build(); fRange.setDataValidation(rule);

newDefinedName()

newDefinedName(): FDefinedNameBuilder

Create a new defined name builder.

Returns

FDefinedNameBuilder

  • The defined name builder.

Example

const fWorkbook = univerAPI.getActiveWorkbook(); const definedNameBuilder = univerAPI.newDefinedName() .setRef('Sheet1!$A$1') .setName('MyDefinedName') .setComment('This is a comment'); console.log(definedNameBuilder); fWorkbook.insertDefinedNameBuilder(definedNameBuilder.build());

newParagraphStyle()

newParagraphStyle(style?): ParagraphStyleBuilder

Create a new paragraph style.

Parameters

ParameterTypeDescription
style?IParagraphStyleThe paragraph style

Returns

ParagraphStyleBuilder

The new paragraph style instance

Example

const richText = univerAPI.newRichText({ body: { dataStream: 'Hello World\r\n' } }); const paragraphStyle = univerAPI.newParagraphStyle({ textStyle: { ff: 'Arial', fs: 12, it: univerAPI.Enum.BooleanNumber.TRUE, bl: univerAPI.Enum.BooleanNumber.TRUE } }); richText.insertParagraph(paragraphStyle); const range = univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1'); range.setRichTextValueForCell(richText);

newParagraphStyleValue()

newParagraphStyleValue(style?): ParagraphStyleValue

Create a new paragraph style value.

Parameters

ParameterTypeDescription
style?IParagraphStyleThe paragraph style

Returns

ParagraphStyleValue

The new paragraph style value instance

Example

const paragraphStyleValue = univerAPI.newParagraphStyleValue();

newRichText()

newRichText(data?): RichTextBuilder

Create a new rich text.

Parameters

ParameterTypeDescription
data?IDocumentData

Returns

RichTextBuilder

The new rich text instance

Example

const richText = univerAPI.newRichText({ body: { dataStream: 'Hello World\r\n' } }); const range = univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1'); range.setRichTextValueForCell(richText);

newRichTextValue()

newRichTextValue(data): RichTextValue

Create a new rich text value.

Parameters

ParameterTypeDescription
dataIDocumentDataThe rich text data

Returns

RichTextValue

The new rich text value instance

Example

const richTextValue = univerAPI.newRichTextValue({ body: { dataStream: 'Hello World\r\n' } }); const range = univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1'); range.setRichTextValueForCell(richTextValue);

newTextDecoration()

newTextDecoration(decoration?): TextDecorationBuilder

Create a new text decoration.

Parameters

ParameterTypeDescription
decoration?ITextDecorationThe text decoration

Returns

TextDecorationBuilder

The new text decoration instance

Example

const decoration = univerAPI.newTextDecoration();

newTextStyle()

newTextStyle(style?): TextStyleBuilder

Create a new text style.

Parameters

ParameterTypeDescription
style?ITextStyleThe text style

Returns

TextStyleBuilder

The new text style instance

Example

const textStyle = univerAPI.newTextStyle();

newTextStyleValue()

newTextStyleValue(style?): TextStyleValue

Create a new text style value.

Parameters

ParameterTypeDescription
style?ITextStyleThe text style

Returns

TextStyleValue

The new text style value instance

Example

const textStyleValue = univerAPI.newTextStyleValue();

newTheadComment()

newTheadComment(): FTheadCommentBuilder

Create a new thread comment

Returns

FTheadCommentBuilder

The thead comment builder

Example

// Create a new comment const richText = univerAPI.newRichText().insertText('hello univer'); const commentBuilder = univerAPI.newTheadComment() .setContent(richText) .setPersonId('mock-user-id') .setDateTime(new Date('2025-02-21 14:22:22')) .setId('mock-comment-id') .setThreadId('mock-thread-id'); // Add the comment to the cell A1 const fWorkbook = univerAPI.getActiveWorkbook(); const fWorksheet = fWorkbook.getActiveSheet(); const cell = fWorksheet.getRange('A1'); const result = await cell.addCommentAsync(commentBuilder); console.log(result);

onBeforeCommandExecute()

onBeforeCommandExecute(callback): IDisposable

Register a callback that will be triggered before invoking a command.

Parameters

ParameterTypeDescription
callbackCommandListenerThe callback.

Returns

IDisposable

The disposable instance.

Deprecated

use univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (event) => {}) instead.


onCommandExecuted()

onCommandExecuted(callback): IDisposable

Register a callback that will be triggered when a command is invoked.

Parameters

ParameterTypeDescription
callbackCommandListenerThe callback.

Returns

IDisposable

The disposable instance.

Deprecated

use univerAPI.addEvent(univerAPI.Event.CommandExecuted, (event) => {}) instead.


onCommentAdded()

onCommentAdded(callback): IDisposable

Parameters

ParameterType
callback(event) => void

Returns

IDisposable

Deprecated

use univerAPI.addEvent(univerAPI.Event.CommentAdded, (params) => {}) as instead


onCommentDeleted()

onCommentDeleted(callback): IDisposable

Parameters

ParameterType
callback(event) => void

Returns

IDisposable

Deprecated

use univerAPI.addEvent(univerAPI.Event.CommentDeleted, (params) => {}) as instead


onCommentResolved()

onCommentResolved(callback): IDisposable

Parameters

ParameterType
callback(event) => void

Returns

IDisposable

Deprecated

use univerAPI.addEvent(univerAPI.Event.CommentResolved, (params) => {}) as instead


onCommentUpdated()

onCommentUpdated(callback): IDisposable

Parameters

ParameterType
callback(event) => void

Returns

IDisposable

Deprecated

use univerAPI.addEvent(univerAPI.Event.CommentUpdated, (params) => {}) as instead


onUniverSheetCreated()

onUniverSheetCreated(callback): IDisposable

Parameters

ParameterType
callback(workbook) => void

Returns

IDisposable

Deprecated

Use univerAPI.addEvent(univerAPI.Event.UnitCreated, () => {})


openDialog()

openDialog(dialog): IDisposable

Open a dialog.

Parameters

ParameterTypeDescription
dialogIDialogPartMethodOptionsthe dialog options

Returns

IDisposable

the disposable object

Example

import { Button } from '@univerjs/design'; univerAPI.openDialog({ id: 'mock-dialog-id', width: 500, title: { label: 'Dialog Title', }, children: { label: 'Dialog Content', }, footer: { title: ( <> <Button onClick={() => { console.log('Cancel clicked') }}>Cancel</Button> <Button type="primary" onClick={() => { console.log('Confirm clicked') }} style={{marginLeft: '10px'}}>Confirm</Button> </> ) }, draggable: true, mask: true, maskClosable: true, });

openSidebar()

openSidebar(params): IDisposable

Open a sidebar.

Parameters

ParameterTypeDescription
paramsISidebarMethodOptionsthe sidebar options

Returns

IDisposable

the disposable object

Example

univerAPI.openSidebar({ id: 'mock-sidebar-id', width: 300, header: { label: 'Sidebar Header', }, children: { label: 'Sidebar Content', }, footer: { label: 'Sidebar Footer', }, onClose: () => { console.log('Sidebar closed') }, });

openSiderbar()

openSiderbar(params): IDisposable

Open a sidebar.

Parameters

ParameterTypeDescription
paramsISidebarMethodOptionsthe sidebar options

Returns

IDisposable

the disposable object

Deprecated

Please use univerAPI.openSidebar instead.


paste()

paste(): Promise<boolean>

Paste into the current selected position of the currently focused unit from your system clipboard.

Returns

Promise<boolean>

whether the paste operation is successful

Example

// Prevent failure due to loss of focus when executing copy and paste code in the console, // this example listens for the cell click event and executes the copy and paste code. univerAPI.addEvent(univerAPI.Event.CellClicked, async (params) => { const fWorkbook = univerAPI.getActiveWorkbook(); const fWorksheet = fWorkbook.getActiveSheet(); // Copy the range A1:B2 to the clipboard const fRange = fWorksheet.getRange('A1:B2'); fRange.activate().setValues([ [1, 2], [3, 4] ]); await univerAPI.copy(); // Paste the copied content to the range C1:D2 const fRange2 = fWorksheet.getRange('C1'); fRange2.activate(); await univerAPI.paste(); // Check the pasted content console.log(fWorksheet.getRange('C1:D2').getValues()); // [[1, 2], [3, 4]] });

redo()

redo(): Promise<boolean>

Redo an editing on the currently focused document.

Returns

Promise<boolean>

redo result

Example

univerAPI.redo();

registerComponent()

registerComponent( name, component, options?): IDisposable

Register an component.

Parameters

ParameterTypeDescription
namestringThe name of the component.
componentComponentTypeThe component.
options?IComponentOptionsThe options of the component.

Returns

IDisposable

The disposable object.

Example

const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet(); // Register a range loading component const RangeLoading = () => { const divStyle = { width: '100%', height: '100%', backgroundColor: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' as const, display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, transformOrigin: 'top left', }; return ( <div style={divStyle}> Loading... </div> ); }; univerAPI.registerComponent('RangeLoading', RangeLoading); // Add the range loading component covering the range A1:C3 const range = fWorksheet.getRange('A1:C3'); const disposeable = fWorksheet.addFloatDomToRange(range, { componentKey: 'RangeLoading' }, {}, 'myRangeLoading'); setTimeout(() => { disposeable?.dispose(); }, 2000);

registerFunction()

registerFunction(config): IDisposable

Register a function to the spreadsheet.

Parameters

ParameterTypeDescription
configIRegisterFunctionParamsThe configuration of the function.

Returns

IDisposable

The disposable instance.

Deprecated

Use univerAPI.getFormula().registerFunction instead.


registerSheetColumnHeaderExtension()

registerSheetColumnHeaderExtension(unitId, ...extensions): IDisposable

Register sheet column header render extensions.

Parameters

ParameterTypeDescription
unitIdstringThe unit id of the spreadsheet.
extensionsSheetExtension[]The extensions to register.

Returns

IDisposable

The disposable instance.


registerSheetMainExtension()

registerSheetMainExtension(unitId, ...extensions): IDisposable

Register sheet main render extensions.

Parameters

ParameterTypeDescription
unitIdstringThe unit id of the spreadsheet.
extensionsSheetExtension[]The extensions to register.

Returns

IDisposable

The disposable instance.


registerSheetRowHeaderExtension()

registerSheetRowHeaderExtension(unitId, ...extensions): IDisposable

Register sheet row header render extensions.

Parameters

ParameterTypeDescription
unitIdstringThe unit id of the spreadsheet.
extensionsSheetExtension[]The extensions to register.

Returns

IDisposable

The disposable instance.


registerUIPart()

registerUIPart(key, component): IDisposable

Register an component to a built-in UI part

Parameters

ParameterTypeDescription
keyBuiltInUIPartthe built-in UI part
componentanythe react component

Returns

IDisposable

Example

univerAPI.registerUIPart(univerAPI.Enum.BuiltInUIPart.CUSTOM_HEADER, () => React.createElement('h1', null, 'Custom Header'));

runOnServer()

runOnServer( scriptNameOrId, func, ... params): Promise<string>

Execute a function in a Uniscript on the server.

Parameters

ParameterTypeDescription
scriptNameOrIdstringThe name or the ID of the Uniscript to run. Name should end with “.us”.
funcstringThe function in the Uniscript to run
paramsany[]Parameters to the function

Returns

Promise<string>


setCrosshairHighlightColor()

setCrosshairHighlightColor(color): FUniver

Set the color of the crosshair highlight.

Parameters

ParameterTypeDescription
colorstringThe color of the crosshair highlight, if the color not has alpha channel, the alpha channel will be set to 0.5

Returns

FUniver

The FUniver instance for chaining

Example

univerAPI.setCrosshairHighlightColor('#FF0000'); // or univerAPI.setCrosshairHighlightColor('rgba(232, 11, 11, 0.2)');

setCrosshairHighlightEnabled()

setCrosshairHighlightEnabled(enabled): FUniver

Enable or disable crosshair highlight.

Parameters

ParameterTypeDescription
enabledbooleanWhether to enable the crosshair highlight

Returns

FUniver

The FUniver instance for chaining

Example

univerAPI.setCrosshairHighlightEnabled(true);

setCurrent()

setCurrent(unitId): void

Set a unit as the current unit and render a unit in the workbench’s main area. If you have multiple units in Univer, you should call this method to render the unit.

Parameters

ParameterTypeDescription
unitIdstringUnit to be rendered.

Returns

void

Example

Let’s assume you have created two units, unit1 and unit2. Univer is rendering unit1 and you want to render unit2.

univerAPI.setCurrent('unit2');

This will render unit2 in the workbench’s main area.


setUIVisible()

setUIVisible(key, visible): FUniver

Set the visibility of a built-in UI part.

Parameters

ParameterTypeDescription
keyBuiltInUIPartthe built-in UI part
visiblebooleanthe visibility

Returns

FUniver

the FUniver instance for chaining example

// Hide header, footer, and toolbar univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false) .setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, false) .setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, false); // Show in 3 seconds setTimeout(() => { univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, true) .setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, true) .setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, true); }, 3000);

showMessage()

showMessage(options): FUniver

Show a message.

Parameters

ParameterType
optionsIMessageProps

Returns

FUniver

the FUniver instance for chaining

Example

univerAPI.showMessage({ content: 'Success', type: 'success', duration: 3000, });

syncExecuteCommand()

syncExecuteCommand<P, R>( id, params?, options?): R

Execute a command with the given id and parameters synchronously.

Type Parameters

Type ParameterDefault type
P extends objectobject
Rboolean

Parameters

ParameterTypeDescription
idstringIdentifier of the command.
params?PParameters of this execution.
options?IExecutionOptionsOptions of this execution.

Returns

R

The result of the execution. It is a boolean value by default which indicates the command is executed.

Example

univerAPI.syncExecuteCommand('sheet.command.set-range-values', { value: { v: "Hello, Univer!" }, range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } });

undo()

undo(): Promise<boolean>

Undo an editing on the currently focused document.

Returns

Promise<boolean>

undo result

Example

univerAPI.undo();

newAPI()

static newAPI(wrapped): FUniver

Create an FUniver instance, if the injector is not provided, it will create a new Univer instance.

Parameters

ParameterTypeDescription
wrappedanyThe Univer instance or injector instance.

Returns

FUniver

  • The FUniver instance.

Static

Example

const univerAPI = FUniver.newAPI(univer);