API Reference

FUniver

The root Facade API for creating and finding units, subscribing to events, and accessing shared services. In Preset Mode, use the univerAPI returned by createUniver. In Plugin Mode, create it with FUniver.newAPI(univer) after registering the required plugins.

The shared UI methods updateMenuConfig(), createMenu(), and createSubmenu() require @univerjs/ui/facade in plugin mode. See menu configuration by product for Sheets, Docs, Slides, Boards, and PDFs, including the boundary between the Ribbon and the Boards canvas toolbar.

Access

After registering your plugins and importing their Facade entries, call FUniver.newAPI(univer) to obtain univerAPI. With presets, use the univerAPI returned by createUniver.

Setup

Register @univerjs/core or a preset that includes it. In plugin mode, import @univerjs/core/facade. Additional methods below require their listed plugin packages. See Facade setup.

@univerjs/core

FUniver.addEvent

Add an event listener

TypeScript
addEvent<T extends keyof IEventParamConfig>(event: T, callback: (params: IEventParamConfig[T]) => void): IDisposable

Parameters

  • event — Required. key of event
  • callback — Required. callback when event triggered

Returns

A disposable that removes the event listener.

Examples

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

Types: IDisposable · IEventParamConfig

Package: @univerjs/core · Type definitions

FUniver.disposeUnit

Disposes the document, workbook, or other Univer unit identified by unitId, unloading it from the application.

TypeScript
disposeUnit(unitId: string): boolean

Parameters

  • unitId — Required. The ID of the unit to dispose.

Returns

Whether the Univer instance is disposed successfully.

Examples

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

Package: @univerjs/core · Type definitions

FUniver.Enum

Enums exposed by the registered Facade extensions.

TypeScript
readonly Enum: FEnum

Types: FEnum

Package: @univerjs/core · Type definitions

FUniver.Event

Event names to use with addEvent.

TypeScript
readonly Event: FEventName

Types: FEventName

Package: @univerjs/core · Type definitions

FUniver.executeCommand

Execute a command with the given id and parameters.

TypeScript
executeCommand<P extends object = object, R = boolean>(id: string, params?: P, options?: IExecutionOptions): Promise<R>

Parameters

  • id — Required. Identifier of the command.
  • params — Optional. Parameters of this execution.
  • options — Optional. Options of this execution.

Returns

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

Examples

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

Types: Promise · IExecutionOptions

Package: @univerjs/core · Type definitions

FUniver.getCurrentLifecycleStage

Get the current lifecycle stage.

TypeScript
getCurrentLifecycleStage(): LifecycleStages

Returns

  • The current lifecycle stage.

Examples

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

Types: LifecycleStages

Package: @univerjs/core · Type definitions

FUniver.getCurrentLocale

Get the current locale.

TypeScript
getCurrentLocale(): string

Returns

The current locale identifier.

Examples

TypeScript
const currentLocale = univerAPI.getCurrentLocale()console.log(currentLocale)

Package: @univerjs/core · Type definitions

FUniver.getCurrentRegion

Get the region currently used for locale-sensitive formatting.

TypeScript
getCurrentRegion(): string

Returns

The current region identifier.

Examples

TypeScript
const currentRegion = univerAPI.getCurrentRegion()console.log(currentRegion)

Package: @univerjs/core · Type definitions

FUniver.getCurrentTheme

Get the theme currently used by Univer.

TypeScript
getCurrentTheme(): Theme

Returns

The current theme.

Examples

TypeScript
const theme = univerAPI.getCurrentTheme()console.log(theme.primary[600])

Types: Theme

Package: @univerjs/core · Type definitions

FUniver.getLocales

Get the locales for the current locale.

TypeScript
getLocales(): ILanguagePack | undefined

Returns

The locales object for the current locale, it returns undefined if the locales is not loaded.

Examples

TypeScript
const locales = univerAPI.getLocales()console.log(locales)

Types: ILanguagePack

Package: @univerjs/core · Type definitions

FUniver.getUserManager

Gets the facade for reading the current user.

TypeScript
getUserManager(): FUserManager

Returns

The user manager facade.

Examples

TypeScript
const user = univerAPI.getUserManager().getCurrentUser()

Types: FUserManager

Package: @univerjs/core · Type definitions

FUniver.isDarkMode

Whether Univer is currently using dark mode.

TypeScript
isDarkMode(): boolean

Returns

Whether dark mode is enabled.

Examples

TypeScript
const darkMode = univerAPI.isDarkMode()

Package: @univerjs/core · Type definitions

FUniver.loadLocales

Load locales for the given locale.

TypeScript
loadLocales(locale: string, locales: ILanguagePack): void

Parameters

  • locale — Required. A unique locale identifier.
  • locales — Required. The locales object containing the translations.

Examples

TypeScript
univerAPI.loadLocales('esES', {  'Hello World': 'Hola Mundo',})

Types: ILanguagePack

Package: @univerjs/core · Type definitions

FUniver.newAPI

Creates a Facade API instance for an existing Univer instance or its injector.

TypeScript
static newAPI(wrapped: Univer | Injector): FUniver

Parameters

  • wrapped — Required. The Univer instance or injector instance.

Returns

  • The FUniver instance.

Examples

TypeScript
const univerAPI = FUniver.newAPI(univer)

Types: FUniver · Univer · Injector

Package: @univerjs/core · Type definitions

FUniver.newBlob

Create a new blob.

TypeScript
newBlob(): FBlob

Returns

The new blob instance

Examples

TypeScript
const blob = univerAPI.newBlob()

Types: FBlob

Package: @univerjs/core · Type definitions

FUniver.newParagraphStyle

Create a new paragraph style.

This is an advanced document-model API. Application and agent code should normally use newRichText().paragraph({ ... }).

TypeScript
newParagraphStyle(style?: IParagraphStyle): ParagraphStyleBuilder

Parameters

  • style — Optional. The paragraph style

Returns

The new paragraph style instance

Types: ParagraphStyleBuilder · IParagraphStyle

Package: @univerjs/core · Type definitions

FUniver.newParagraphStyleValue

Create a new paragraph style value.

TypeScript
newParagraphStyleValue(style?: IParagraphStyle): ParagraphStyleValue

Parameters

  • style — Optional. The paragraph style

Returns

The new paragraph style value instance

Examples

TypeScript
const paragraphStyleValue = univerAPI.newParagraphStyleValue()

Types: ParagraphStyleValue · IParagraphStyle

Package: @univerjs/core · Type definitions

FUniver.newRichText

Create a new rich text.

TypeScript
newRichText(): RichTextBuilder

Returns

The new rich text instance

Examples

TypeScript
const richText = univerAPI  .newRichText()  .text('Read ')  .link('Univer documentation', 'https://docs.univer.ai')  .text(' for details.')

Types: RichTextBuilder

Package: @univerjs/core · Type definitions

FUniver.newRichTextFromDocumentData

Create a rich-text builder from raw Univer document data.

This is an advanced integration escape hatch for importers and adapters. Application and agent code should use the fluent builder returned by newRichText().

TypeScript
newRichTextFromDocumentData(data: IDocumentData): RichTextBuilder

Parameters

  • data — Required. Raw Univer document data.

Returns

A rich-text builder initialized with the supplied document data.

Types: RichTextBuilder · IDocumentData

Package: @univerjs/core · Type definitions

FUniver.newRichTextValue

Create a new rich text value.

This is an advanced integration escape hatch for callers that already own Univer document data. Application and agent code should prefer the fluent value returned by newRichText().

TypeScript
newRichTextValue(data: IDocumentData): RichTextValue

Parameters

  • data — Required. The raw Univer document data.

Returns

The new rich text value instance

Types: RichTextValue · IDocumentData

Package: @univerjs/core · Type definitions

FUniver.newTextDecoration

Create a new text decoration.

TypeScript
newTextDecoration(decoration?: ITextDecoration): TextDecorationBuilder

Parameters

  • decoration — Optional. The text decoration

Returns

The new text decoration instance

Examples

TypeScript
const decoration = univerAPI.newTextDecoration()

Types: TextDecorationBuilder · ITextDecoration

Package: @univerjs/core · Type definitions

FUniver.newTextStyle

Create a new text style.

TypeScript
newTextStyle(style?: ITextStyle): TextStyleBuilder

Parameters

  • style — Optional. The text style

Returns

The new text style instance

Examples

TypeScript
const textStyle = univerAPI.newTextStyle()

Types: TextStyleBuilder · ITextStyle

Package: @univerjs/core · Type definitions

FUniver.newTextStyleValue

Create a new text style value.

TypeScript
newTextStyleValue(style?: ITextStyle): TextStyleValue

Parameters

  • style — Optional. The text style

Returns

The new text style value instance

Examples

TypeScript
const textStyleValue = univerAPI.newTextStyleValue()

Types: TextStyleValue · ITextStyle

Package: @univerjs/core · Type definitions

FUniver.redo

Redo an editing on the currently focused document.

TypeScript
redo(): Promise<boolean>

Returns

redo result

Examples

TypeScript
await univerAPI.redo()

Types: Promise

Package: @univerjs/core · Type definitions

FUniver.registerEventHandler

Registers a factory for the subscription that produces an event. The factory starts when listeners exist and its subscription is disposed when the last listener is removed.

TypeScript
registerEventHandler: (event: string, handler: () => IDisposable | Subscription) => IDisposable

Returns

A disposable that unregisters the factory and disposes its active subscription.

Types: IDisposable · Subscription

Package: @univerjs/core · Type definitions

FUniver.setDirection

Set the current layout direction.

TypeScript
setDirection(direction: 'ltr' | 'rtl'): void

Parameters

  • direction — Required. The layout direction.

Examples

TypeScript
univerAPI.setDirection('rtl')

Package: @univerjs/core · Type definitions

FUniver.setLocale

Set the current locale.

TypeScript
setLocale(locale: string): void

Parameters

  • locale — Required. A unique locale identifier.

Examples

TypeScript
univerAPI.setLocale('esES')

Package: @univerjs/core · Type definitions

FUniver.setRegion

Set the region used for locale-sensitive formatting.

TypeScript
setRegion(region: string): void

Parameters

  • region — Required. A unique region identifier.

Examples

TypeScript
univerAPI.setRegion('enUS')

Package: @univerjs/core · Type definitions

FUniver.setTheme

Set the theme used by Univer.

TypeScript
setTheme(theme: Theme): void

Parameters

  • theme — Required. The complete theme to use.

Examples

TypeScript
import { defaultTheme } from '@univerjs/themes'univerAPI.setTheme({  ...defaultTheme,  primary: {    ...defaultTheme.primary,    600: '#274fee',  },})

Types: Theme

Package: @univerjs/core · Type definitions

FUniver.syncExecuteCommand

Execute a command with the given id and parameters synchronously.

TypeScript
syncExecuteCommand<P extends object = object, R = boolean>(id: string, params?: P, options?: IExecutionOptions): R

Parameters

  • id — Required. Identifier of the command.
  • params — Optional. Parameters of this execution.
  • options — Optional. Options of this execution.

Returns

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

Examples

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

Types: IExecutionOptions

Package: @univerjs/core · Type definitions

FUniver.toggleDarkMode

Toggle dark mode on or off.

TypeScript
toggleDarkMode(isDarkMode: boolean): void

Parameters

  • isDarkMode — Required. Whether the dark mode is enabled.

Examples

TypeScript
univerAPI.toggleDarkMode(true)

Package: @univerjs/core · Type definitions

FUniver.undo

Undo an editing on the currently focused document.

TypeScript
undo(): Promise<boolean>

Returns

undo result

Examples

TypeScript
await univerAPI.undo()

Types: Promise

Package: @univerjs/core · Type definitions

FUniver.Util

Utility functions exposed by the registered Facade extensions.

TypeScript
readonly Util: FUtil

Types: FUtil

Package: @univerjs/core · Type definitions

@univerjs/docs

FUniver.createDocument

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

TypeScript
createDocument(data: Partial<IDocumentData>, options?: ICreateUnitOptions): FDocument

Parameters

  • data — Required. The snapshot of the document.
  • options — Optional. The options of creating the document.

Returns

The document API instance.

Examples

TypeScript
const fDocument = univerAPI.createDocument({ id: 'document-01', title: 'Document1' })console.log(fDocument)

Types: FDocument · Partial · IDocumentData · ICreateUnitOptions

Package: @univerjs/docs · Type definitions

FUniver.getActiveDocument

Get the currently focused Univer document.

TypeScript
getActiveDocument(): FDocument | null

Returns

The currently focused Univer document API instance, or null if there is no focused Univer document.

Examples

TypeScript
const fDocument = univerAPI.getActiveDocument()console.log(fDocument)

Types: FDocument

Package: @univerjs/docs · Type definitions

FUniver.getDocument

Get the document API handler by the document id.

TypeScript
getDocument(id: string): FDocument | null

Parameters

  • id — Required. The document id.

Returns

The document API instance corresponding to the document id, or null if not found.

Examples

TypeScript
const fDocument = univerAPI.getDocument('document-01')console.log(fDocument)

Types: FDocument

Package: @univerjs/docs · Type definitions

@univerjs/engine-formula

FUniver.getFormula

Gets the formula engine facade for calculation, parsing, and dependency queries.

TypeScript
getFormula(): FFormula

Returns

The formula engine facade.

Examples

TypeScript
const formula = univerAPI.getFormula()await formula.onCalculationResultApplied()

Types: FFormula

Package: @univerjs/engine-formula · Type definitions

@univerjs/network

FUniver.createSocket

Set WebSocket URL for WebSocketService

TypeScript
createSocket(url: string): ISocket

Parameters

  • url — Required. WebSocket URL

Returns

WebSocket instance

Examples

TypeScript
// Replace the URL with the address of your own WebSocket serviceconst ws = univerAPI.createSocket('wss://47.100.177.253:8449/ws')ws.open$.subscribe(() => {  console.log('websocket opened')  ws.send('hello')})ws.message$.subscribe((message) => {  console.log('websocket message', message)  const content = JSON.parse(message.data).content  if (!content.includes('command')) {    return  }  const commandInfo = JSON.parse(content)  const { command, options } = commandInfo  const { id, params } = command  // Upon receiving collaborative data, it is locally saved  univerAPI.executeCommand(id, params, options)})ws.close$.subscribe(() => {  console.log('websocket closed')})ws.error$.subscribe((error) => {  console.log('websocket error', error)})univerAPI.addEvent(univerAPI.Event.CommandExecuted, ({ id, type, params, options }) => {  // Only synchronize local mutations  if (    type !== univerAPI.Enum.CommandType.MUTATION ||    options?.fromCollab ||    options?.onlyLocal ||    id === 'doc.mutation.rich-text-editing'  ) {    return  }  const commandInfo = JSON.stringify({    command: { id, type, params },    options: { fromCollab: true },  })  ws.send(commandInfo)})

Types: ISocket

Package: @univerjs/network · Type definitions

FUniver.getNetwork

Get the network API of Univer, with the help of which you can send HTTP requests.

TypeScript
getNetwork(): FNetwork

Types: FNetwork

Package: @univerjs/network · Type definitions

@univerjs/sheets

FUniver.createWorkbook

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

TypeScript
createWorkbook(data: Partial<IWorkbookData>, options?: ICreateUnitOptions): FWorkbook

Parameters

  • data — Required. The snapshot of the spreadsheet.
  • options — Optional. The options of creating the spreadsheet.

Returns

The spreadsheet API instance.

Examples

TypeScript
const fWorkbook = univerAPI.createWorkbook({ id: 'workbook-01', name: 'Workbook1' })console.log(fWorkbook)

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

TypeScript
const fWorkbook = univerAPI.createWorkbook(  { id: 'workbook-01', name: 'Workbook1' },  { makeCurrent: false },)console.log(fWorkbook)

Types: FWorkbook · Partial · IWorkbookData · ICreateUnitOptions

Package: @univerjs/sheets · Type definitions

FUniver.getActiveSheet

Get the active sheet.

TypeScript
getActiveSheet(): { workbook: FWorkbook; worksheet: FWorksheet; } | null

Returns

The active sheet.

Examples

TypeScript
const target = univerAPI.getActiveSheet()if (!target) throw new Error('target is not available')const { workbook, worksheet } = targetconsole.log(workbook, worksheet)

Types: FWorkbook · FWorksheet

Package: @univerjs/sheets · Type definitions

FUniver.getActiveWorkbook

Get the currently focused Univer spreadsheet.

TypeScript
getActiveWorkbook(): FWorkbook | null

Returns

The currently focused Univer spreadsheet API instance, or null if there is no active spreadsheet.

Examples

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

Types: FWorkbook

Package: @univerjs/sheets · Type definitions

FUniver.getSheetCommandTarget

Get the target of the sheet.

TypeScript
getSheetCommandTarget(params?: { unitId?: string; subUnitId?: string; sheetId?: string; }): { workbook: FWorkbook; worksheet: FWorksheet; unitId: string; subUnitId: string; } | null

Parameters

  • params — Optional. Default: {}. Target IDs from the command parameters. Omitted IDs use the current workbook and active sheet.

Returns

The resolved workbook, worksheet, and their IDs, or null if the target cannot be resolved.

Examples

TypeScript
univerAPI.addEvent(univerAPI.Event.CommandExecuted, (event) => {  const target = univerAPI.getSheetCommandTarget(event.params)  if (!target) return  const { workbook, worksheet } = target  console.log(workbook, worksheet)})

Types: FWorkbook · FWorksheet

Package: @univerjs/sheets · Type definitions

FUniver.getWorkbook

Get the spreadsheet API handler by the spreadsheet id.

TypeScript
getWorkbook(id: string): FWorkbook | null

Parameters

  • id — Required. The spreadsheet id.

Returns

The spreadsheet API instance corresponding to the spreadsheet id, or null if not found.

Examples

TypeScript
const fWorkbook = univerAPI.getWorkbook('workbook-01')console.log(fWorkbook)

Types: FWorkbook

Package: @univerjs/sheets · Type definitions

FUniver.setFreezeSync

Set whether to enable synchronize the frozen state to other users in real-time collaboration.

TypeScript
setFreezeSync(enabled: boolean): void

Parameters

  • enabled — Required. Whether to enable freeze sync. Default is true.

Examples

TypeScript
// Disable freeze syncuniverAPI.setFreezeSync(false)

Package: @univerjs/sheets · Type definitions

@univerjs/sheets-crosshair-highlight

FUniver.getCrosshairHighlightEnabled

Get whether the crosshair highlight is enabled.

TypeScript
getCrosshairHighlightEnabled(): boolean

Returns

Whether the crosshair highlight is enabled

Examples

TypeScript
console.log(univerAPI.getCrosshairHighlightEnabled())

Package: @univerjs/sheets-crosshair-highlight · Type definitions

FUniver.setCrosshairHighlightEnabled

Enable or disable crosshair highlight.

TypeScript
setCrosshairHighlightEnabled(enabled: boolean): FUniver

Parameters

  • enabled — Required. Whether to enable the crosshair highlight

Returns

The FUniver instance for chaining

Examples

TypeScript
univerAPI.setCrosshairHighlightEnabled(true)

Types: FUniver

Package: @univerjs/sheets-crosshair-highlight · Type definitions

@univerjs/sheets-data-validation

FUniver.newDataValidation

Creates a new instance of FDataValidationBuilder

TypeScript
newDataValidation(): FDataValidationBuilder

Returns

A new instance of the FDataValidationBuilder class

Examples

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getSheetByName('Sheet1')if (!fWorksheet) throw new Error('fWorksheet is not available')// Create a new data validation rule that requires a number between 1 and 10 fot the range A1:B10const 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)

Types: FDataValidationBuilder

Package: @univerjs/sheets-data-validation · Type definitions

@univerjs/sheets-drawing-ui

FUniver.registerURLImageDownloader

Register a custom image downloader for URL images

TypeScript
registerURLImageDownloader(downloader: (url: string) => Promise<string>): IDisposable

Parameters

  • downloader — Required. The downloader function that takes a URL and returns a base64 string

Returns

A disposable object to unregister the downloader

Examples

TypeScript
const disposable = univerAPI.registerURLImageDownloader(async (url) => {  const response = await fetch(url)  const blob = await response.blob()  const base64 = await new Promise<string>((resolve) => {    const reader = new FileReader()    reader.onloadend = () => resolve(reader.result as string)    reader.readAsDataURL(blob)  })  return base64})

Types: IDisposable · Promise

Package: @univerjs/sheets-drawing-ui · Type definitions

@univerjs/sheets-find-replace

FUniver.createTextFinderAsync

Create a text-finder for the current univer.

TypeScript
createTextFinderAsync(text: string): Promise<FTextFinder | null>

Parameters

  • text — Required. The text to find.

Returns

A promise that resolves to the text-finder instance.

Examples

TypeScript
// Assume the current sheet is empty sheet.const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getSheetByName('Sheet1')if (!fWorksheet) throw new Error('fWorksheet is not available')// Set some values to the range A1:D10.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})

Types: FTextFinder · Promise

Package: @univerjs/sheets-find-replace · Type definitions

@univerjs/sheets-formula-ui

FUniver.showRangeSelectorDialog

Shows the range selector dialog.

TypeScript
showRangeSelectorDialog(opts: IShowRangeSelectorDialogOptions): Promise<IUnitRangeName[]>

Parameters

  • opts — Required. The options of the range selector dialog.

Returns

The selected ranges.

Examples

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getSheetByName('Sheet1')if (!fWorksheet) throw new Error('fWorksheet is not available')const unitId = fWorkbook.getId()await univerAPI.showRangeSelectorDialog({  unitId,  subUnitId: fWorksheet.getSheetId(),  initialValue: [    {      unitId,      sheetName: fWorksheet.getSheetName(),      range: fWorksheet.getRange('A1:B2').getRange(),    },  ],  maxRangeCount: 2,  supportAcrossSheet: true,  callback: (ranges, isCancel) => {    // Handle the selected ranges    console.log(ranges, isCancel)  },})

Types: IUnitRangeName · Promise · IShowRangeSelectorDialogOptions

Package: @univerjs/sheets-formula-ui · Type definitions

@univerjs/sheets-ui

FUniver.getProtectedRangeShadowStrategy

Get the current global strategy for showing the protected range shadow.

TypeScript
getProtectedRangeShadowStrategy(): 'always' | 'non-editable' | 'non-viewable' | 'none'

Returns

The current shadow strategy

Examples

TypeScript
const currentStrategy = univerAPI.getProtectedRangeShadowStrategy()console.log(currentStrategy) // 'none', 'always', 'non-editable', or 'non-viewable'

Package: @univerjs/sheets-ui · Type definitions

FUniver.getProtectedRangeShadowStrategy$

Get an observable of the global strategy for showing the protected range shadow. This allows you to listen for strategy changes across all workbooks.

TypeScript
getProtectedRangeShadowStrategy$(): Observable<'always' | 'non-editable' | 'non-viewable' | 'none'>

Returns

An observable that emits the current shadow strategy

Examples

TypeScript
const subscription = univerAPI.getProtectedRangeShadowStrategy$().subscribe((strategy) => {  console.log('Global strategy changed to:', strategy)  // Update UI or perform other actions})// Later, unsubscribe to clean upsubscription.unsubscribe()

Types: Observable

Package: @univerjs/sheets-ui · Type definitions

FUniver.pasteIntoSheet

Paste clipboard data or custom data into the active sheet at the current selection position.

TypeScript
pasteIntoSheet(htmlContent?: string, textContent?: string, files?: File[]): Promise<boolean>

Parameters

  • htmlContent — Optional. The HTML content from the clipboard or custom data.
  • textContent — Optional. The plain text content from the clipboard or custom data.
  • files — Optional. The files from the clipboard or custom data.

Returns

A promise that resolves to true if the paste operation was successful, otherwise false.

Examples

TSX
// Listen for the paste event and call the pasteIntoSheet methoddocument.addEventListener('paste', async (event) => {  const htmlContent = event.clipboardData.getData('text/html')  const textContent = event.clipboardData.getData('text/plain')  const files = Array.from(event.clipboardData.items)    .map((item) => (item.kind === 'file' ? item.getAsFile() : undefined))    .filter(Boolean)  await univerAPI.pasteIntoSheet(htmlContent, textContent, files)})// Or paste custom datauniverAPI.pasteIntoSheet('<b>Bold Text</b>', 'Bold Text')

Types: Promise · File

Package: @univerjs/sheets-ui · Type definitions

FUniver.registerCellCustomRender

Register cell custom render.

TypeScript
registerCellCustomRender(customRender: Nullable<ICellCustomRender[]>, effect?: InterceptorEffectEnum, priority?: number): IDisposable

Parameters

  • customRender — Required. Custom render function.
  • effect — Optional. Default: InterceptorEffectEnum.Style. The effect of the interceptor, style or value.
  • priority — Optional. The priority of the interceptor.

Types: IDisposable · Nullable · ICellCustomRender · InterceptorEffectEnum

Package: @univerjs/sheets-ui · Type definitions

FUniver.registerSheetColumnHeaderExtension

Register sheet column header render extensions.

TypeScript
registerSheetColumnHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable

Parameters

  • unitId — Required. The unit id of the spreadsheet.
  • extensions — Required. The extensions to register.

Returns

The disposable instance.

Types: IDisposable · SheetExtension

Package: @univerjs/sheets-ui · Type definitions

FUniver.registerSheetMainExtension

Register sheet main render extensions.

TypeScript
registerSheetMainExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable

Parameters

  • unitId — Required. The unit id of the spreadsheet.
  • extensions — Required. The extensions to register.

Returns

The disposable instance.

Types: IDisposable · SheetExtension

Package: @univerjs/sheets-ui · Type definitions

FUniver.registerSheetRowHeaderExtension

Register sheet row header render extensions.

TypeScript
registerSheetRowHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable

Parameters

  • unitId — Required. The unit id of the spreadsheet.
  • extensions — Required. The extensions to register.

Returns

The disposable instance.

Types: IDisposable · SheetExtension

Package: @univerjs/sheets-ui · Type definitions

FUniver.setPermissionDialogVisible

Set visibility of unauthorized pop-up window

TypeScript
setPermissionDialogVisible(visible: boolean): void

Parameters

  • visible — Required. visibility of unauthorized pop-up window

Examples

TypeScript
const univerAPI = FUniver.newAPI(univer)univerAPI.setPermissionDialogVisible(false)

Package: @univerjs/sheets-ui · Type definitions

FUniver.setProtectedRangeShadowStrategy

Set the global strategy for showing the protected range shadow. This will apply to all workbooks in the current Univer instance.

TypeScript
setProtectedRangeShadowStrategy(strategy: 'always' | 'non-editable' | 'non-viewable' | 'none'): void

Parameters

  • strategy — Required. The shadow strategy to apply
  • 'always': Show shadow for all protected ranges
  • 'non-editable': Only show shadow for ranges that cannot be edited
  • 'non-viewable': Only show shadow for ranges that cannot be viewed
  • 'none': Never show shadow for protected ranges

Examples

TypeScript
// Always show shadows (default)univerAPI.setProtectedRangeShadowStrategy('always')// Only show shadows for non-editable rangesuniverAPI.setProtectedRangeShadowStrategy('non-editable')// Only show shadows for non-viewable rangesuniverAPI.setProtectedRangeShadowStrategy('non-viewable')// Never show shadowsuniverAPI.setProtectedRangeShadowStrategy('none')

Package: @univerjs/sheets-ui · Type definitions

@univerjs/thread-comment

FUniver.createCommentAsync

Creates a root comment on a drawing, page element, page position, or Base record anchor. For a sheet-cell comment, use FRange.addCommentAsync; for document text, use FDocumentTextRange.createCommentAsync.

TypeScript
createCommentAsync(options: ThreadComment.ICreateThreadCommentOptions): Promise<boolean>

Parameters

  • options — Required. Comment content, owner IDs, stable anchor, and optional caller-controlled IDs.

Returns

true when the command succeeds; otherwise, false.

Throws

If the content is empty or the anchor is invalid.

Examples

TypeScript
const workbook = univerAPI.getActiveWorkbook()if (!workbook) {  throw new Error('No active workbook')}const sheet = workbook.getActiveSheet()const image = sheet.getImages()[0]if (!image) {  throw new Error('No image to comment on')}await univerAPI.createCommentAsync({  unitId: workbook.getId(),  subUnitId: sheet.getSheetId(),  anchor: {    kind: univerAPI.Enum.ThreadCommentAnchorKind.SHEET_DRAWING,    elementId: image.getId(),  },  content: 'Verify this value.',})

Types: Promise · ThreadComment.ICreateThreadCommentOptions

Package: @univerjs/thread-comment · Type definitions

FUniver.deleteCommentAsync

Deletes one comment, or the complete root and reply tree when deleteThread is true.

TypeScript
deleteCommentAsync(options: ThreadComment.IDeleteThreadCommentOptions): Promise<boolean>

Parameters

  • options — Required. Owning IDs, target comment ID, and the optional whole-thread flag.

Returns

true when the delete command succeeds; otherwise, false.

Examples

TypeScript
const [comment] = univerAPI.getComments({ resolved: false })if (comment) {  await univerAPI.deleteCommentAsync({    unitId: comment.unitId,    subUnitId: comment.subUnitId,    commentId: comment.root.id,    deleteThread: true,  })}

Types: Promise · ThreadComment.IDeleteThreadCommentOptions

Package: @univerjs/thread-comment · Type definitions

FUniver.getComments

Queries locally loaded threads by unit, subunit, anchor kind, author, or resolution state.

TypeScript
getComments(query?: ThreadComment.IThreadCommentQuery): ThreadComment.IFacadeThreadCommentInfo[]

Parameters

  • query — Optional. Default: {}. Optional filters. Omit the argument to return every locally loaded thread.

Returns

Matching root threads, their replies, anchor kinds, parsed anchors, and related user IDs.

Examples

TypeScript
const workbook = univerAPI.getActiveWorkbook()if (!workbook) {  throw new Error('No active workbook')}const openAgentReviews = univerAPI.getComments({  unitIds: [workbook.getId()],  authorIds: ['agent-reviewer'],  anchorKinds: [univerAPI.Enum.ThreadCommentAnchorKind.SHEET_DRAWING],  resolved: false,})const sheetCellReviews = univerAPI.getComments({  anchorKinds: [univerAPI.Enum.ThreadCommentAnchorKind.SHEET_CELL],})

Types: ThreadComment.IFacadeThreadCommentInfo · ThreadComment.IThreadCommentQuery

Package: @univerjs/thread-comment · Type definitions

FUniver.listCommentsAsync

Synchronizes locally known threads from the configured datasource, then applies the same filters as getComments. This method does not discover thread IDs that have never been loaded into the model.

TypeScript
listCommentsAsync(query?: ThreadComment.IThreadCommentQuery): Promise<ThreadComment.IFacadeThreadCommentInfo[]>

Parameters

  • query — Optional. Default: {}. Optional filters. Omit the argument to synchronize and return every known thread.

Returns

A promise resolving to the synchronized matching threads.

Examples

TypeScript
const workbook = univerAPI.getActiveWorkbook()if (!workbook) {  throw new Error('No active workbook')}const comments = await univerAPI.listCommentsAsync({  unitIds: [workbook.getId()],  anchorKinds: [univerAPI.Enum.ThreadCommentAnchorKind.SHEET_DRAWING],  resolved: false,})comments.forEach(({ root, children, anchorKind, anchor }) => {  console.log(root.id, children.length, anchorKind, anchor)})

Types: ThreadComment.IFacadeThreadCommentInfo · Promise · ThreadComment.IThreadCommentQuery

Package: @univerjs/thread-comment · Type definitions

FUniver.replyCommentAsync

Adds a reply to an existing root thread.

TypeScript
replyCommentAsync(options: ThreadComment.IReplyThreadCommentOptions): Promise<boolean>

Parameters

  • options — Required. Reply content and the owning unit, subunit, and thread IDs.

Returns

true when the reply is created. Returns false when the root thread is not loaded or the command fails.

Throws

If the content is empty.

Examples

TypeScript
const [thread] = univerAPI.getComments({ resolved: false })if (thread) {  await univerAPI.replyCommentAsync({    unitId: thread.unitId,    subUnitId: thread.subUnitId,    threadId: thread.threadId,    content: 'Verified.',  })}

Types: Promise · ThreadComment.IReplyThreadCommentOptions

Package: @univerjs/thread-comment · Type definitions

FUniver.resolveCommentAsync

Resolves a thread. Pass resolved: false to reopen it.

TypeScript
resolveCommentAsync(options: ThreadComment.IResolveThreadCommentOptions): Promise<boolean>

Parameters

  • options — Required. Owning IDs, a comment ID in the thread, and the desired resolution state.

Returns

true when the resolve command succeeds; otherwise, false.

Examples

TypeScript
const [comment] = univerAPI.getComments({ resolved: false })if (comment) {  await univerAPI.resolveCommentAsync({    unitId: comment.unitId,    subUnitId: comment.subUnitId,    commentId: comment.root.id,  })}

Types: Promise · ThreadComment.IResolveThreadCommentOptions

Package: @univerjs/thread-comment · Type definitions

FUniver.updateCommentAsync

Updates the content or attachments of an existing root comment or reply.

TypeScript
updateCommentAsync(options: ThreadComment.IUpdateThreadCommentOptions): Promise<boolean>

Parameters

  • options — Required. Updated content and the owning unit, subunit, and comment IDs.

Returns

true when the update command succeeds; otherwise, false.

Throws

If the content is empty.

Examples

TypeScript
const [comment] = univerAPI.getComments({ resolved: false })if (comment) {  await univerAPI.updateCommentAsync({    unitId: comment.unitId,    subUnitId: comment.subUnitId,    commentId: comment.root.id,    content: 'Updated review result.',  })}

Types: Promise · ThreadComment.IUpdateThreadCommentOptions

Package: @univerjs/thread-comment · Type definitions

@univerjs/ui

FUniver.addFonts

Append custom fonts to the font list.

TypeScript
addFonts(fonts: IFontConfig[]): void

Parameters

  • fonts — Required. The array of font configurations to add.

Examples

TypeScript
univerAPI.addFonts([  {    value: 'CustomFont1',    label: 'Custom Font 1',    category: 'sans-serif',  },  {    value: 'CustomFont2',    label: 'Custom Font 2',    category: 'serif',  },])

Types: IFontConfig

Package: @univerjs/ui · Type definitions

FUniver.copy

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

TypeScript
copy(): Promise<boolean>

Returns

whether the copy operation is successful

Examples

TypeScript
// 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.getSheetByName('Sheet1')  if (!fWorksheet) return  // 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]]})

Types: Promise

Package: @univerjs/ui · Type definitions

FUniver.createMenu

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

TypeScript
createMenu(menuItem: IFacadeMenuItem): FMenu

Parameters

  • menuItem — Required. the menu item

Returns

the FMenu object

Examples

TSX
// Univer Icon can be viewed at https://docs.univer.ai/iconsimport { SmileIcon } from '@univerjs/icons'// Create a custom menu with an univer iconuniverAPI.registerComponent('custom-menu-icon', SmileIcon)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 iconuniverAPI.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 iconuniverAPI  .createMenu({    id: 'custom-menu',    title: 'Custom Menu',    tooltip: 'Custom Menu Tooltip',    action: () => {      console.log('Custom Menu Clicked')    },  })  .appendTo('ribbon.start.others')

Types: FMenu · IFacadeMenuItem

Package: @univerjs/ui · Type definitions

FUniver.createSubmenu

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

TypeScript
createSubmenu(submenuItem: IFacadeSubmenuItem): FSubmenu

Parameters

  • submenuItem — Required. the submenu item

Returns

the FSubmenu object

Examples

TypeScript
// 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')

Types: FSubmenu · IFacadeSubmenuItem

Package: @univerjs/ui · Type definitions

FUniver.getComponentManager

Get the component manager

TypeScript
getComponentManager(): ComponentManager

Returns

The component manager

Examples

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

Types: ComponentManager

Package: @univerjs/ui · Type definitions

FUniver.getShortcut

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

TypeScript
getShortcut(): FShortcut

Returns

the FShortcut object

Examples

TypeScript
const fShortcut = univerAPI.getShortcut()// Disable shortcuts of UniverfShortcut.disableShortcut()// Enable shortcuts of UniverfShortcut.enableShortcut()// Trigger a shortcutconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getSheetByName('Sheet1')if (!fWorksheet) throw new Error('fWorksheet is not available')const fRange = fWorksheet.getRange('A1')fRange.activate()fRange.setValue('Hello Univer')console.log(fRange.getCellStyle().bold) // falseconst 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}

Types: FShortcut

Package: @univerjs/ui · Type definitions

FUniver.getURL

Return the URL of the current page.

TypeScript
getURL(): URL

Returns

the URL object

Examples

TypeScript
console.log(univerAPI.getURL())

Types: URL

Package: @univerjs/ui · Type definitions

FUniver.isUIVisible

Get the visibility of a built-in UI part.

TypeScript
isUIVisible(ui: BuiltInUIPart): boolean

Parameters

  • ui — Required.

Returns

the visibility

Examples

TypeScript
// Hide headeruniverAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false)console.log(univerAPI.isUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER)) // false

Types: BuiltInUIPart

Package: @univerjs/ui · Type definitions

FUniver.openDialog

Open a dialog.

TypeScript
openDialog(dialog: IDialogPartMethodOptions): IDisposable

Parameters

  • dialog — Required. the dialog options

Returns

the disposable object

Examples

TSX
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          variant="primary"          onClick={() => {            console.log('Confirm clicked')          }}          style={{ marginLeft: '10px' }}        >          Confirm        </Button>      </>    ),  },  draggable: true,  mask: true,  maskClosable: true,})

Types: IDisposable · IDialogPartMethodOptions

Package: @univerjs/ui · Type definitions

FUniver.openSidebar

Open a sidebar.

TypeScript
openSidebar(params: ISidebarMethodOptions): IDisposable

Parameters

  • params — Required. the sidebar options

Returns

the disposable object

Examples

TypeScript
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')  },})

Types: IDisposable · ISidebarMethodOptions

Package: @univerjs/ui · Type definitions

FUniver.paste

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

TypeScript
paste(): Promise<boolean>

Returns

whether the paste operation is successful

Examples

TypeScript
// 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.getSheetByName('Sheet1')  if (!fWorksheet) return  // 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]]})

Types: Promise

Package: @univerjs/ui · Type definitions

FUniver.registerComponent

Register an component.

TypeScript
registerComponent(name: string, component: ComponentType, options?: IComponentOptions): IDisposable

Parameters

  • name — Required. The name of the component.
  • component — Required. The component.
  • options — Optional. The options of the component.

Returns

The disposable object.

Examples

TSX
const fWorksheet = univerAPI.getActiveWorkbook().getSheetByName('Sheet1')if (!fWorksheet) throw new Error('fWorksheet is not available')// Register a range loading componentconst 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:C3const range = fWorksheet.getRange('A1:C3')const disposeable = fWorksheet.addFloatDomToRange(  range,  { componentKey: 'RangeLoading' },  {},  'myRangeLoading',)setTimeout(() => {  disposeable?.dispose()}, 2000)

Types: IDisposable · ComponentType · IComponentOptions

Package: @univerjs/ui · Type definitions

FUniver.registerUIPart

Register an component to a built-in UI part

TypeScript
registerUIPart(key: BuiltInUIPart, component: ComponentType): IDisposable

Parameters

  • key — Required. the built-in UI part
  • component — Required. the react component

Examples

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

Types: IDisposable · BuiltInUIPart · ComponentType

Package: @univerjs/ui · Type definitions

FUniver.setCurrent

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.

TypeScript
setCurrent(unitId: string): void

Parameters

  • unitId — Required. Unit to be rendered.

Examples

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

TypeScript
univerAPI.setCurrent('unit2')

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

Package: @univerjs/ui · Type definitions

FUniver.setRibbonType

Set the ribbon layout type.

TypeScript
setRibbonType(ribbonType: RibbonType): FUniver

Parameters

  • ribbonType — Required. The ribbon layout type.

Returns

the FUniver instance for chaining

Examples

TypeScript
univerAPI.setRibbonType('grid')

Types: FUniver · RibbonType

Package: @univerjs/ui · Type definitions

FUniver.setUIVisible

Set the visibility of a built-in UI part.

TypeScript
setUIVisible(ui: BuiltInUIPart, visible: boolean): FUniver

Parameters

  • ui — Required.
  • visible — Required. the visibility

Returns

the FUniver instance for chaining

Examples

TypeScript
// Hide header, footer, and toolbaruniverAPI  .setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false)  .setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, false)  .setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, false)// Show in 3 secondssetTimeout(() => {  univerAPI    .setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, true)    .setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, true)    .setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, true)}, 3000)

Types: FUniver · BuiltInUIPart

Package: @univerjs/ui · Type definitions

FUniver.showMessage

Show a message.

TypeScript
showMessage(options: IMessageProps): FUniver

Parameters

  • options — Required. Message content, type, duration, and other display options.

Returns

the FUniver instance for chaining

Examples

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

Types: FUniver · IMessageProps

Package: @univerjs/ui · Type definitions

FUniver.updateMenuConfig

Merge menu overrides and refresh the UI immediately. Overrides also apply to menus registered later. Use the same configuration as the UI plugin or preset's menu option.

TypeScript
updateMenuConfig(config: MenuConfig): FUniver

Parameters

  • config — Required. Overrides keyed by menu item ID, ribbon tab key, or ribbon group key. Unspecified properties keep their current values. Lower order values come first among siblings. gridLayout applies only to the grid ribbon and uses 1-based positions within a two-row group.

Returns

the FUniver instance for chaining

Examples

TypeScript
univerAPI.updateMenuConfig({  'ribbon.insert': { order: -1 },  'ribbon.start.format': { order: -1 },  'sheet.command.set-range-bold': {    order: 0,    gridLayout: { row: 2, column: 2, showLabel: true, width: 80 },  },  'sheet.command.set-range-italic': {    gridLayout: { row: 2, column: 1 },  },})

Types: FUniver · MenuConfig

Package: @univerjs/ui · Type definitions

@univerjs/watermark

FUniver.addWatermark

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

TypeScript
addWatermark(type: IWatermarkTypeEnum.Text, config: ITextWatermarkConfig): FUniveraddWatermark(type: IWatermarkTypeEnum.Image, config: IImageWatermarkConfig): FUniver

Parameters

  • type — Required. The type of watermark to add is Text.
  • config — Required. The configuration object for the text type watermark.

Returns

The FUniver instance for chaining.

Throws

Throws an error if the watermark type is unknown.

Examples

TypeScript
univerAPI.addWatermark('text', {  content: 'Univer',  fontSize: 20,  repeat: true,})
TypeScript
univerAPI.addWatermark('image', {  url: 'https://avatars.githubusercontent.com/u/61444807?s=48&v=4',  width: 100,  height: 100,})

Types: FUniver · IWatermarkTypeEnum.Text · ITextWatermarkConfig · IWatermarkTypeEnum.Image · IImageWatermarkConfig

Package: @univerjs/watermark · Type definitions

FUniver.deleteWatermark

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

TypeScript
deleteWatermark(): FUniver

Returns

The FUniver instance for chaining.

Examples

TypeScript
univerAPI.deleteWatermark()

Types: FUniver

Package: @univerjs/watermark · Type definitions

@univerjs-pro/bases

FUniver.createBase

Create a new Base unit with the given snapshot and options.

TypeScript
createBase(snapshot?: Partial<IBaseSnapshot>, options?: ICreateUnitOptions): FBase

Parameters

  • snapshot — Optional. Default: {}. The persisted Base model snapshot.
  • options — Optional. Options for creating the unit.

Returns

The Base facade API instance.

Examples

TypeScript
const fBase = univerAPI.createBase({  id: 'base-1',  name: 'Roadmap',})console.log(fBase)

Types: FBase · Partial · IBaseSnapshot · ICreateUnitOptions

Package: @univerjs-pro/bases · Type definitions

FUniver.getActiveBase

Get the currently active Base unit.

TypeScript
getActiveBase(): FBase | null

Returns

The active Base facade, or null if no Base is active.

Examples

TypeScript
const fBase = univerAPI.getActiveBase()console.log(fBase)

Types: FBase

Package: @univerjs-pro/bases · Type definitions

FUniver.getBase

Get a Base unit by id.

TypeScript
getBase(baseId: string): FBase | null

Parameters

  • baseId — Required. The id of the Base unit to retrieve.

Returns

The Base facade, or null if the unit does not exist or is not a Base unit.

Examples

TypeScript
const fBase = univerAPI.getBase('base-1')console.log(fBase)

Types: FBase

Package: @univerjs-pro/bases · Type definitions

FUniver.getBases

Get all Base units in the current Univer instance.

TypeScript
getBases(): FBase[]

Returns

An array of Base facade instances.

Examples

TypeScript
const fBases = univerAPI.getBases()const snapshots = fBases.map((fBase) => fBase.save())console.log(snapshots)

Types: FBase

Package: @univerjs-pro/bases · Type definitions

@univerjs-pro/bases-exchange-client

FUniver.exportBaseBySnapshotAsync

Export Base snapshot data as an XLSX, CSV, or TSV file.

TypeScript
exportBaseBySnapshotAsync(snapshot: IBaseSnapshot, format?: ExchangeFormat, tableId?: string): Promise<File | undefined>

Parameters

  • snapshot — Required. Base data to export
  • format — Optional. Output format
  • tableId — Optional. Base table ID to export when the format is CSV or TSV

Returns

A promise that resolves to the exported file, or undefined when the export does not produce a file

Examples

TypeScript
import { ExchangeFormat } from '@univerjs-pro/exchange-client'const base = univerAPI.getActiveBase()if (base) {  const file = await univerAPI.exportBaseBySnapshotAsync(base.save(), ExchangeFormat.CSV)  if (file) {    univerAPI.downloadFile(file, 'table', ExchangeFormat.CSV)  }}

Types: File · Promise · IBaseSnapshot · ExchangeFormat

Package: @univerjs-pro/bases-exchange-client · Type definitions

FUniver.exportBaseByUnitIdAsync

Export a persisted Base unit as an XLSX, CSV, or TSV file.

TypeScript
exportBaseByUnitIdAsync(unitId: string, format?: ExchangeFormat, tableId?: string): Promise<File | undefined>

Parameters

  • unitId — Required. ID of the Base unit to export
  • format — Optional. Output format
  • tableId — Optional. Base table ID to export when the format is CSV or TSV

Returns

A promise that resolves to the exported file, or undefined when the export does not produce a file

Examples

TypeScript
import { ExchangeFormat } from '@univerjs-pro/exchange-client'const file = await univerAPI.exportBaseByUnitIdAsync(unitId, ExchangeFormat.XLSX)if (file) {  univerAPI.downloadFile(file, 'database', ExchangeFormat.XLSX)}

Types: File · Promise · ExchangeFormat

Package: @univerjs-pro/bases-exchange-client · Type definitions

FUniver.importBaseToSnapshotAsync

Import an XLSX, XLS, CSV, or TSV file into Base snapshot data.

TypeScript
importBaseToSnapshotAsync(file: File | string): Promise<IBaseSnapshot | undefined>

Parameters

  • file — Required. File object or URL of the file to import

Returns

A promise that resolves to Base data, or undefined when the import does not produce a snapshot

Examples

TypeScript
// Accepts a File objectconst baseData = await univerAPI.importBaseToSnapshotAsync(file)// Or accepts a URL to a remote file// const baseData = await univerAPI.importBaseToSnapshotAsync('https://example.com/database.csv');

Types: IBaseSnapshot · Promise · File

Package: @univerjs-pro/bases-exchange-client · Type definitions

FUniver.importBaseToUnitIdAsync

Import an XLSX, XLS, CSV, or TSV file into a persisted Base unit.

TypeScript
importBaseToUnitIdAsync(file: File | string): Promise<string | undefined>

Parameters

  • file — Required. File object or URL of the file to import

Returns

A promise that resolves to the imported unit ID, or undefined when the import does not produce a unit

Examples

TypeScript
// Accepts a File objectconst unitId = await univerAPI.importBaseToUnitIdAsync(file)// Or accepts a URL to a remote file// const unitId = await univerAPI.importBaseToUnitIdAsync('https://example.com/database.xlsx');

Types: Promise · File

Package: @univerjs-pro/bases-exchange-client · Type definitions

FUniver.transformBaseDataToSnapshotJsonAsync

Convert Base data into snapshot JSON accepted by the exchange service.

TypeScript
transformBaseDataToSnapshotJsonAsync(baseData: IBaseSnapshot): Promise<ISnapshotBlockJson>

Parameters

  • baseData — Required. Base data to convert

Returns

A promise that resolves to Snapshot JSON containing Base metadata and encoded Sheet blocks

Examples

TypeScript
const base = univerAPI.getActiveBase()if (base) {  const snapshotJson = await univerAPI.transformBaseDataToSnapshotJsonAsync(base.save())}

Types: ISnapshotBlockJson · Promise · IBaseSnapshot

Package: @univerjs-pro/bases-exchange-client · Type definitions

FUniver.transformSnapshotJsonToBaseDataAsync

Convert Base snapshot JSON returned by the exchange service into Base data.

TypeScript
transformSnapshotJsonToBaseDataAsync(json: ISnapshotBlockJsonResponse): Promise<IBaseSnapshot>

Parameters

  • json — Required. Snapshot JSON and Sheet blocks returned by the exchange service

Returns

A promise that resolves to Base data

Examples

TypeScript
const baseData = await univerAPI.transformSnapshotJsonToBaseDataAsync(snapshotJson)

Types: IBaseSnapshot · Promise · ISnapshotBlockJsonResponse

Package: @univerjs-pro/bases-exchange-client · Type definitions

@univerjs-pro/bases-ui

FUniver.getBaseUI

Returns the Base UI facade for the current injector, sharing its selection, editor, and UI state services.

TypeScript
getBaseUI(): FBaseUI

Types: FBaseUI

Package: @univerjs-pro/bases-ui · Type definitions

@univerjs-pro/boards

FUniver.createBoard

Creates a board unit and returns its facade.

TypeScript
createBoard(data?: Partial<IBoardData>, options?: ICreateUnitOptions): FBoard

Parameters

  • data — Optional. Default: {}. Optional board snapshot fields such as name.
  • options — Optional. Optional Univer unit creation options.

Returns

A board facade for the created unit.

Examples

TypeScript
const board = univerAPI.createBoard({ name: 'Planning Board' })console.log(board.getId())

Types: FBoard · Partial · IBoardData · ICreateUnitOptions

Package: @univerjs-pro/boards · Type definitions

FUniver.getActiveBoard

Gets the active board facade.

TypeScript
getActiveBoard(): FBoard | null

Returns

The active board facade, or null when the current Univer unit is not a board.

Examples

TypeScript
const board = univerAPI.getActiveBoard()if (!board) throw new Error('No active board')const descriptors = board.describeElements()console.log(descriptors.length)

Types: FBoard

Package: @univerjs-pro/boards · Type definitions

FUniver.getBoard

Gets a board facade by unit id.

Use this when a board unit id comes from application state or a previous facade call. Prefer getActiveBoard() when the target is the user's current board; agent plans should store generated element ids, not generated unit ids.

TypeScript
getBoard(id: string): FBoard | null

Parameters

  • id — Required. Board unit id from application state or a previous facade call.

Returns

The board facade, or null when no board unit exists for the id.

Examples

TypeScript
const activeBoard = univerAPI.getActiveBoard()if (!activeBoard) throw new Error('No active board')console.log(univerAPI.getBoard(activeBoard.getId()))

Types: FBoard

Package: @univerjs-pro/boards · Type definitions

@univerjs-pro/boards-exchange-client

FUniver.exportBoardBySnapshotAsync

Export Board snapshot data as a PPTX file.

TypeScript
exportBoardBySnapshotAsync(snapshot: IBoardData): Promise<File | undefined>

Parameters

  • snapshot — Required. Board data to export

Returns

A promise that resolves to the exported PPTX file, or undefined when the export does not produce a file

Examples

TypeScript
const board = univerAPI.getActiveBoard()if (board) {  const file = await univerAPI.exportBoardBySnapshotAsync(board.save())  if (file) {    univerAPI.downloadFile(file, 'board', 'pptx')  }}

Types: File · Promise · IBoardData

Package: @univerjs-pro/boards-exchange-client · Type definitions

FUniver.exportBoardByUnitIdAsync

Export a persisted Board unit as a PPTX file.

TypeScript
exportBoardByUnitIdAsync(unitId: string): Promise<File | undefined>

Parameters

  • unitId — Required. ID of the Board unit to export

Returns

A promise that resolves to the exported PPTX file, or undefined when the export does not produce a file

Examples

TypeScript
const file = await univerAPI.exportBoardByUnitIdAsync(unitId)if (file) {  univerAPI.downloadFile(file, 'board', 'pptx')}

Types: File · Promise

Package: @univerjs-pro/boards-exchange-client · Type definitions

FUniver.transformBoardDataToSnapshotJsonAsync

Convert Board data into snapshot JSON accepted by the exchange service.

TypeScript
transformBoardDataToSnapshotJsonAsync(boardData: IBoardData): Promise<ISnapshotBlockJson>

Parameters

  • boardData — Required. Board data to convert

Returns

A promise that resolves to encoded Snapshot JSON

Examples

TypeScript
const board = univerAPI.getActiveBoard()if (board) {  const snapshotJson = await univerAPI.transformBoardDataToSnapshotJsonAsync(board.save())}

Types: ISnapshotBlockJson · Promise · IBoardData

Package: @univerjs-pro/boards-exchange-client · Type definitions

FUniver.transformSnapshotJsonToBoardDataAsync

Convert Board snapshot JSON returned by the exchange service into Board data.

TypeScript
transformSnapshotJsonToBoardDataAsync(json: ISnapshotBlockJsonResponse): Promise<IBoardData>

Parameters

  • json — Required. Snapshot JSON returned by the exchange service

Returns

A promise that resolves to Board data

Examples

TypeScript
const boardData = await univerAPI.transformSnapshotJsonToBoardDataAsync(snapshotJson)

Types: IBoardData · Promise · ISnapshotBlockJsonResponse

Package: @univerjs-pro/boards-exchange-client · Type definitions

@univerjs-pro/collaboration-client

FUniver.getCollaboration

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

TypeScript
getCollaboration(): FCollaboration

Returns

The collaboration instance.

Examples

TypeScript
const collaboration = univerAPI.getCollaboration()

Types: FCollaboration

Package: @univerjs-pro/collaboration-client · Type definitions

FUniver.loadServerUnit

Load the server unit by the given unit id and unit type.

TypeScript
loadServerUnit(unitId: string, unitType: UniverInstanceType, subUnitId?: string): Promise<UnitModel | null>

Parameters

  • unitId — Required. The unit id.
  • unitType — Required. The unit type.
  • subUnitId — Optional. The sub unit id.

Returns

The promise with the unit model.

Examples

TypeScript
const unitModel = await univerAPI.loadServerUnit(  'unitId',  univerAPI.Enum.UniverInstanceType.UNIVER_SHEET,)console.log(unitModel, unitModel?.getSnapshot())

Types: UnitModel · Promise · UniverInstanceType

Package: @univerjs-pro/collaboration-client · Type definitions

FUniver.loadServerUnitOfRevision

Load the server unit by the given unit id, unit type and revision.

TypeScript
loadServerUnitOfRevision(unitId: string, unitType: UniverInstanceType, rev: number): Promise<UnitModel | null>

Parameters

  • unitId — Required. The unit id.
  • unitType — Required. The unit type.
  • rev — Required. The revision number.

Returns

The promise with the unit model.

Examples

TypeScript
const unitModel = await univerAPI.loadServerUnitOfRevision(  'unitId',  univerAPI.Enum.UniverInstanceType.UNIVER_SHEET,  1,)console.log(unitModel, unitModel?.getSnapshot())

Types: UnitModel · Promise · UniverInstanceType

Package: @univerjs-pro/collaboration-client · Type definitions

@univerjs-pro/collaboration-client-ui

FUniver.runOnServer

Execute a function in a Uniscript on the server.

TypeScript
runOnServer(scriptNameOrId: string, func: string, ...params: any[]): Promise<string>

Parameters

  • scriptNameOrId — Required. The name or the ID of the Uniscript to run. Name should end with ".us".
  • func — Required. The function in the Uniscript to run
  • params — Required. Parameters to the function

Types: Promise

Package: @univerjs-pro/collaboration-client-ui · Type definitions

@univerjs-pro/docs-exchange-client

FUniver.exportDocBySnapshotAsync

Export Document snapshot data as DOCX.

TypeScript
exportDocBySnapshotAsync(snapshot: IDocumentData): Promise<File | undefined>

Parameters

  • snapshot — Required. Document data to export

Returns

A promise that resolves to the DOCX file, or undefined

Examples

TypeScript
const snapshot = univerAPI.getActiveDocument().save()const file = await univerAPI.exportDocBySnapshotAsync(snapshot)if (file) univerAPI.downloadFile(file, 'document', 'docx')

Types: File · Promise · IDocumentData

Package: @univerjs-pro/docs-exchange-client · Type definitions

FUniver.exportDocByUnitIdAsync

Export a persisted Document unit as DOCX.

TypeScript
exportDocByUnitIdAsync(unitId: string): Promise<File | undefined>

Parameters

  • unitId — Required. Document unit ID

Returns

A promise that resolves to the DOCX file, or undefined

Examples

TypeScript
const file = await univerAPI.exportDocByUnitIdAsync(unitId)if (file) univerAPI.downloadFile(file, 'document', 'docx')

Types: File · Promise

Package: @univerjs-pro/docs-exchange-client · Type definitions

FUniver.importDocToSnapshotAsync

Import a DOCX file into Document snapshot data.

TypeScript
importDocToSnapshotAsync(file: File | string, options?: IExchangeDocImportOption): Promise<IDocumentData | undefined>

Parameters

  • file — Required. File object or URL of the DOCX file to import
  • options — Optional. Document type to use for the imported document

Returns

A promise that resolves to Document data, or undefined

Examples

TypeScript
import { ExchangeDocType } from '@univerjs-pro/exchange-client'const snapshot = await univerAPI.importDocToSnapshotAsync(file, {  docType: ExchangeDocType.TRADITIONAL,})// const snapshot = await univerAPI.importDocToSnapshotAsync('https://example.com/document.docx');

Types: IDocumentData · Promise · File · IExchangeDocImportOption

Package: @univerjs-pro/docs-exchange-client · Type definitions

FUniver.importDocToUnitIdAsync

Import a DOCX file into a persisted Document unit.

TypeScript
importDocToUnitIdAsync(file: File | string, options?: IExchangeDocImportOption): Promise<string | undefined>

Parameters

  • file — Required. File object or URL of the DOCX file to import
  • options — Optional. Document type to use for the imported document

Returns

A promise that resolves to the imported unit ID, or undefined

Examples

TypeScript
import { ExchangeDocType } from '@univerjs-pro/exchange-client'const unitId = await univerAPI.importDocToUnitIdAsync(file, { docType: ExchangeDocType.MODERN })// const unitId = await univerAPI.importDocToUnitIdAsync('https://example.com/document.docx');

Types: Promise · File · IExchangeDocImportOption

Package: @univerjs-pro/docs-exchange-client · Type definitions

FUniver.transformDocumentDataToSnapshotJsonAsync

Convert Document data into exchange Snapshot JSON.

TypeScript
transformDocumentDataToSnapshotJsonAsync(documentData: IDocumentData): Promise<ISnapshotBlockJson>

Parameters

  • documentData — Required. Document data to convert

Returns

A promise that resolves to Snapshot JSON

Examples

TypeScript
const snapshotJson = await univerAPI.transformDocumentDataToSnapshotJsonAsync(documentData)

Types: ISnapshotBlockJson · Promise · IDocumentData

Package: @univerjs-pro/docs-exchange-client · Type definitions

FUniver.transformSnapshotJsonToDocumentDataAsync

Convert exchange Snapshot JSON into Document data.

TypeScript
transformSnapshotJsonToDocumentDataAsync(json: ISnapshotBlockJsonResponse): Promise<IDocumentData>

Parameters

  • json — Required. Snapshot JSON returned by the exchange service

Returns

A promise that resolves to Document data

Examples

TypeScript
const documentData = await univerAPI.transformSnapshotJsonToDocumentDataAsync(snapshotJson)

Types: IDocumentData · Promise · ISnapshotBlockJsonResponse

Package: @univerjs-pro/docs-exchange-client · Type definitions

@univerjs-pro/edit-history

FUniver.compareUnitData

Compares two fully materialized UnitData snapshots with the semantic adapter registered for the unit type.

Worktree resolution and mutation materialization must happen before this method is called. The result is serializable and contains stable entity identities, locations, leaf changes, coverage, and diagnostics. This is a read-only comparison, not a merge or a mutation replay operation. Register the corresponding product History plugin, or register its headless comparison adapter as in the example below. Product adapters compare semantic content, not byte-for-byte snapshot equality: editor selection/zoom, mirrored Board storage aliases, and Base matrix indexes derived from entity order are not extra changes.

Results default to 100 items with leaf changes and no full values. Use query.offset/query.limit to page items and query.contextOffset/query.contextLimit to page Doc alignment independently. For repeated queries over the same snapshots, use prepareUnitComparison() and call query() on its result.

TypeScript
compareUnitData(input: IUnitComparisonInput): IUnitComparisonResult

Parameters

  • input — Required. The two materialized states and optional result query.

Returns

A versioned semantic comparison result suitable for UI and agent consumers.

Throws

If the comparison service or an adapter for input.type has not been registered.

Examples

See createUnitComparisonEngine() for an executable injector-free headless example. In a Univer application, register the selected product History plugin and import @univerjs-pro/edit-history/facade before creating the Facade API.

Types: IUnitComparisonResult · IUnitComparisonInput

Package: @univerjs-pro/edit-history · Type definitions

FUniver.prepareUnitComparison

Prepares a semantic comparison once for repeated filtering and pagination.

Register the selected product History plugin before calling this method. The returned Facade owns no editor state and never mutates either snapshot.

TypeScript
prepareUnitComparison(input: Omit<IUnitComparisonInput, 'query'>): FUnitComparison

Parameters

  • input — Required. Two fully materialized UnitData snapshots and their comparison metadata.

Returns

A prepared comparison Facade whose query() method does not rerun the product algorithm.

Types: FUnitComparison · Omit · IUnitComparisonInput

Package: @univerjs-pro/edit-history · Type definitions

@univerjs-pro/embed

FUniver.createEmbed

Create an embed descriptor and host anchor without materializing provider-backed ResourceRefs.

displayTarget stores the author- or Agent-selected default subview in the host embed resource. Normal user navigation inside the child remains local and does not overwrite this value.

A Sheet floating embed defaults to SheetDrawingAnchorType.Position when host.context.placement is omitted. Pass an explicit Placement when the caller needs a specific Position, Both, or None anchor.

A DocBlock embed accepts host.context.startIndex as a UTF-16 offset in the host document body's dataStream. When it is omitted, the block is appended to the editable body. Unknown context fields and invalid offsets are rejected.

SheetTab, BaseTable, and SlidePage accept a zero-based insertion index and an optional display name. Omitted indices append to the corresponding live collection. SlideFloating and BoardFloating accept an optional target page plus finite bounds. Every built-in surface rejects unknown context fields and invalid values before creating its descriptor or anchor mutations.

TypeScript
createEmbed<TUnitFacade = never, TChildType extends UniverInstanceType = UniverInstanceType, THostSurface extends FEmbedHostSurface = FEmbedHostSurface>(params: ICreateEmbedParams<TChildType, THostSurface>): FEmbed<FResolvedUnitFacade<TUnitFacade, TChildType>>

Parameters

  • params — Required. Embed creation parameters.

Returns

The created embed facade.

Examples

TypeScript

TypeScript
const embed = univerAPI.createEmbed<UniverFacadeTypes.FDocument>({  embedId: 'doc-in-sheet',  host: {    unitId: 'host-unit-id',    surface: univerAPI.Enum.FEmbedHostSurface.SheetFloating,    context: {      subUnitId: 'host-sheet-id',    },  },  content: {    unitType: univerAPI.Enum.UniverInstanceType.UNIVER_DOC,    ref: '#unit=another-unit-id&type=doc',  },})const childDocument = await embed.loadAsync()

Insert a Sheet block at a document model offset

TypeScript
const embed = univerAPI.createEmbed({  host: {    unitId: 'host-document-id',    surface: univerAPI.Enum.FEmbedHostSurface.DocBlock,    context: { startIndex: 42 },  },  content: {    unitType: univerAPI.Enum.UniverInstanceType.UNIVER_SHEET,    ref: '#unit=sheet-unit-id&type=sheet',  },})

Create a Base embed that initially opens a calendar view

TypeScript
const embed = univerAPI.createEmbed({  embedId: 'base-calendar',  host: {    unitId: 'board-unit-id',    surface: univerAPI.Enum.FEmbedHostSurface.BoardFloating,    context: {      left: 120,      top: 100,      width: 1120,      height: 680,    },  },  content: {    unitType: univerAPI.Enum.UniverInstanceType.UNIVER_BASE,    ref: '#unit=base-unit-id&type=base',  },  displayTarget: {    tableId: 'events',    viewId: 'calendar',  },})

Types: FResolvedUnitFacade · FEmbed · ICreateEmbedParams

Package: @univerjs-pro/embed · Type definitions

FUniver.getEmbed

Get one embed by host unit id and embed id.

TypeScript
getEmbed(params: IGetEmbedParams): FEmbed<unknown> | null

Parameters

  • params — Required. Get parameters.

Returns

The embed facade, or null when it does not exist.

Examples

TypeScript

TypeScript
const embed = univerAPI.getEmbed({  hostUnitId: 'host-unit-id',  embedId: 'doc-in-sheet',})

Types: FEmbed · IGetEmbedParams

Package: @univerjs-pro/embed · Type definitions

FUniver.listEmbeds

List active embeds.

TypeScript
listEmbeds(params?: IListEmbedsParams): Array<FEmbed<unknown>>

Parameters

  • params — Optional. Default: {}. List parameters.

Returns

Active embed facades.

Examples

TypeScript

TypeScript
const embeds = univerAPI.listEmbeds({ hostUnitId: 'host-unit-id' })

Types: FEmbed · Array · IListEmbedsParams

Package: @univerjs-pro/embed · Type definitions

FUniver.loadUnitAsync

Load a ResourceRef-targeted unit into the current runtime.

This is the generic facade entry for unit load. Embed-specific callers can use FEmbed.loadAsync, which passes an embed owner.

TypeScript
loadUnitAsync<TUnitFacade = never, TUnitType extends UniverInstanceType | undefined = undefined>(ref: FUnitRef, options?: ILoadUnitAsyncOptions<TUnitType>): Promise<FResolvedUnitFacade<TUnitFacade, TUnitType>>

Parameters

  • ref — Required. The resource reference to load. String input supports canonical self unit ResourceRefs like #unit=<unitId>&type=doc.
  • options — Optional. Default: {}. Optional request controls.

Returns

A promise resolving to the loaded unit facade instance.

Examples

TypeScript

TypeScript
const document = await univerAPI.loadUnitAsync<UniverFacadeTypes.FDocument>(  '#unit=another-unit-id&type=doc',  { unitType: univerAPI.Enum.UniverInstanceType.UNIVER_DOC },)

JavaScript

TypeScript
const document = await univerAPI.loadUnitAsync('#unit=another-unit-id&type=doc', {  unitType: univerAPI.Enum.UniverInstanceType.UNIVER_DOC,})

Types: FResolvedUnitFacade · Promise · FUnitRef · ILoadUnitAsyncOptions

Package: @univerjs-pro/embed · Type definitions

FUniver.removeEmbed

Remove an embed by host unit id and embed id.

TypeScript
removeEmbed(params: IRemoveEmbedParams): boolean

Parameters

  • params — Required. Remove parameters.

Returns

true when the remove command succeeds.

Examples

TypeScript

TypeScript
const removed = univerAPI.removeEmbed({  hostUnitId: 'host-unit-id',  embedId: 'doc-in-sheet',})

Types: IRemoveEmbedParams

Package: @univerjs-pro/embed · Type definitions

@univerjs-pro/engine-chart

FUniver.registerTheme

Registers a Chart theme in this Univer runtime.

The theme is shared by Sheet, Slide, Document, and Board Charts. Use the same name with a Chart builder's setTheme() method to apply it. Registering the same name again replaces the previous theme.

TypeScript
registerTheme(name: string, theme: IEchartTheme): void

Parameters

  • name — Required. The stable name used by Chart builders.
  • theme — Required. The complete Chart theme definition.

Examples

TypeScript
import { UniverTheme1 } from '@univerjs-pro/engine-chart'univerAPI.registerTheme('brand', {  ...UniverTheme1,  themeName: 'brand',  theme: {    ...UniverTheme1.theme,    color: ['#1677ff', '#52c41a', '#faad14'],  },})const fWorkbook = univerAPI.getActiveWorkbook()if (!fWorkbook) throw new Error('No active workbook.')const fWorksheet = fWorkbook.getSheetByName('Sheet1')if (!fWorksheet) throw new Error('Worksheet not found.')const chartInfo = fWorksheet  .newChart(univerAPI.Enum.ChartTypeString.Column)  .setSource('A1:D8')  .setTheme('brand')  .build()await fWorksheet.insertChart(chartInfo)

Types: IEchartTheme

Package: @univerjs-pro/engine-chart · Type definitions

@univerjs-pro/exchange-client

FUniver.downloadFile

Trigger a browser download for a file or blob.

TypeScript
downloadFile(file: File | Blob, filename: string, fileExt: string): void

Parameters

  • file — Required. File or blob to download
  • filename — Required. Filename without extension
  • fileExt — Required. File extension without a leading dot

Examples

TypeScript
const file = await univerAPI.exportSheetByUnitIdAsync(unitId)if (file) univerAPI.downloadFile(file, 'univer', 'xlsx')

Types: File · Blob

Package: @univerjs-pro/exchange-client · Type definitions

@univerjs-pro/pdfs

FUniver.createPdf

Create a PDF unit and return its Facade.

TypeScript
createPdf(data?: Partial<IPdfUnitData>, options?: ICreateUnitOptions): FPdf

Parameters

  • data — Optional. Default: {}. The PDF Unit data. Assign an existing PDF document to data.document. Omit it or pass an empty object to create a blank PDF.
  • options — Optional. Optional unit creation settings.

Returns

The created PDF Facade.

Examples

TypeScript
const pdf = univerAPI.createPdf({})console.log(pdf.getId())

Types: FPdf · Partial · IPdfUnitData · ICreateUnitOptions

Package: @univerjs-pro/pdfs · Type definitions

FUniver.getActivePdf

Return the active PDF unit.

TypeScript
getActivePdf(): FPdf | null

Returns

The active PDF Facade, or null when no PDF is active.

Examples

TypeScript
const pdf = univerAPI.getActivePdf()console.log(pdf?.getName())

Types: FPdf

Package: @univerjs-pro/pdfs · Type definitions

FUniver.getPdf

Return a PDF unit by ID.

TypeScript
getPdf(id: string): FPdf | null

Parameters

  • id — Required. The PDF unit ID.

Returns

The matching PDF Facade, or null when it does not exist.

Examples

TypeScript
const pdf = univerAPI.getPdf('pdf-unit-id')console.log(pdf?.getPages())

Types: FPdf

Package: @univerjs-pro/pdfs · Type definitions

FUniver.getPdfTableThemePresets

Return the built-in PDF table-theme presets.

TypeScript
getPdfTableThemePresets(): ReadonlyArray<Readonly<IPdfTableThemePreset>>

Returns

Detached preset descriptors.

Examples

TypeScript
const presets = univerAPI.getPdfTableThemePresets()console.log(presets)

Types: Readonly · IPdfTableThemePreset · ReadonlyArray

Package: @univerjs-pro/pdfs · Type definitions

@univerjs-pro/pdfs-exchange-client

FUniver.exportPdfBySnapshotAsync

Export PDF snapshot data as a PDF file.

TypeScript
exportPdfBySnapshotAsync(snapshot: IPdfUnitData): Promise<File | undefined>

Parameters

  • snapshot — Required. PDF data to export

Returns

A promise that resolves to the exported PDF file, or undefined when the export does not produce a file

Examples

TypeScript
const pdf = univerAPI.getActivePdf()if (pdf) {  const file = await univerAPI.exportPdfBySnapshotAsync(pdf.save())  if (file) {    univerAPI.downloadFile(file, 'document', 'pdf')  }}

Types: File · Promise · IPdfUnitData

Package: @univerjs-pro/pdfs-exchange-client · Type definitions

FUniver.exportPdfByUnitIdAsync

Export a persisted PDF unit as a PDF file.

TypeScript
exportPdfByUnitIdAsync(unitId: string): Promise<File | undefined>

Parameters

  • unitId — Required. ID of the PDF unit to export

Returns

A promise that resolves to the exported PDF file, or undefined when the export does not produce a file

Examples

TypeScript
const file = await univerAPI.exportPdfByUnitIdAsync(unitId)if (file) {  univerAPI.downloadFile(file, 'document', 'pdf')}

Types: File · Promise

Package: @univerjs-pro/pdfs-exchange-client · Type definitions

FUniver.importPdfToSnapshotAsync

Import a PDF file into PDF snapshot data.

TypeScript
importPdfToSnapshotAsync(file: File | string): Promise<IPdfUnitData | undefined>

Parameters

  • file — Required. File object or URL of the PDF file to import

Returns

A promise that resolves to PDF data, or undefined when the import does not produce a snapshot

Examples

TypeScript
// Accepts a File objectconst pdfData = await univerAPI.importPdfToSnapshotAsync(file)// Or accepts a URL to a remote file// const pdfData = await univerAPI.importPdfToSnapshotAsync('https://example.com/document.pdf');

Types: IPdfUnitData · Promise · File

Package: @univerjs-pro/pdfs-exchange-client · Type definitions

FUniver.importPdfToUnitIdAsync

Import a PDF file into a persisted PDF unit.

TypeScript
importPdfToUnitIdAsync(file: File | string): Promise<string | undefined>

Parameters

  • file — Required. File object or URL of the PDF file to import

Returns

A promise that resolves to the imported unit ID, or undefined when the import does not produce a unit

Examples

TypeScript
// Accepts a File objectconst unitId = await univerAPI.importPdfToUnitIdAsync(file)// Or accepts a URL to a remote file// const unitId = await univerAPI.importPdfToUnitIdAsync('https://example.com/document.pdf');

Types: Promise · File

Package: @univerjs-pro/pdfs-exchange-client · Type definitions

FUniver.transformPdfDataToSnapshotJsonAsync

Convert PDF data into snapshot JSON accepted by the exchange service.

TypeScript
transformPdfDataToSnapshotJsonAsync(pdfData: IPdfUnitData): Promise<ISnapshotBlockJson>

Parameters

  • pdfData — Required. PDF data to convert

Returns

A promise that resolves to encoded Snapshot JSON

Examples

TypeScript
const pdf = univerAPI.getActivePdf()if (pdf) {  const snapshotJson = await univerAPI.transformPdfDataToSnapshotJsonAsync(pdf.save())}

Types: ISnapshotBlockJson · Promise · IPdfUnitData

Package: @univerjs-pro/pdfs-exchange-client · Type definitions

FUniver.transformSnapshotJsonToPdfDataAsync

Convert PDF snapshot JSON returned by the exchange service into PDF data.

TypeScript
transformSnapshotJsonToPdfDataAsync(json: ISnapshotBlockJsonResponse): Promise<IPdfUnitData>

Parameters

  • json — Required. Snapshot JSON returned by the exchange service

Returns

A promise that resolves to PDF data

Examples

TypeScript
const pdfData = await univerAPI.transformSnapshotJsonToPdfDataAsync(snapshotJson)

Types: IPdfUnitData · Promise · ISnapshotBlockJsonResponse

Package: @univerjs-pro/pdfs-exchange-client · Type definitions

@univerjs-pro/sheets-exchange-client

FUniver.exportSheetBySnapshotAsync

Export workbook snapshot data as an XLSX, CSV, or TSV file.

TypeScript
exportSheetBySnapshotAsync(snapshot: IWorkbookData, format?: ExchangeFormat, sheetId?: string): Promise<File | undefined>

Parameters

  • snapshot — Required. Workbook data to export
  • format — Optional. Output format
  • sheetId — Optional. Sheet ID to export when the format is CSV or TSV

Returns

A promise that resolves to the exported file, or undefined when the export does not produce a file

Examples

TypeScript
import { ExchangeFormat } from '@univerjs-pro/exchange-client'const workbook = univerAPI.getActiveWorkbook()if (workbook) {  const snapshot = workbook.save()  const file = await univerAPI.exportSheetBySnapshotAsync(    snapshot,    ExchangeFormat.CSV,    workbook.getActiveSheet().getSheetId(),  )  if (file) {    univerAPI.downloadFile(file, 'active-sheet', ExchangeFormat.CSV)  }}

Types: File · Promise · IWorkbookData · ExchangeFormat

Package: @univerjs-pro/sheets-exchange-client · Type definitions

FUniver.exportSheetByUnitIdAsync

Export a persisted Sheet unit as an XLSX, CSV, or TSV file.

TypeScript
exportSheetByUnitIdAsync(unitId: string, format?: ExchangeFormat, sheetId?: string): Promise<File | undefined>

Parameters

  • unitId — Required. ID of the Sheet unit to export
  • format — Optional. Output format
  • sheetId — Optional. Sheet ID to export when the format is CSV or TSV

Returns

A promise that resolves to the exported file, or undefined when the export does not produce a file

Examples

TypeScript
import { ExchangeFormat } from '@univerjs-pro/exchange-client'const workbook = univerAPI.getActiveWorkbook()if (workbook) {  const file = await univerAPI.exportSheetByUnitIdAsync(workbook.getId(), ExchangeFormat.XLSX)  if (file) {    univerAPI.downloadFile(file, 'budget', ExchangeFormat.XLSX)  }}

Types: File · Promise · ExchangeFormat

Package: @univerjs-pro/sheets-exchange-client · Type definitions

FUniver.importSheetToSnapshotAsync

Import an XLSX, XLS, CSV, or TSV file into workbook snapshot data.

TypeScript
importSheetToSnapshotAsync(file: File | string): Promise<IWorkbookData | undefined>

Parameters

  • file — Required. File object or URL of the file to import

Returns

A promise that resolves to the imported workbook data, or undefined when the import does not produce a snapshot

Examples

TypeScript
// Accepts a File objectconst workbookData = await univerAPI.importSheetToSnapshotAsync(file)// Or accepts a URL to a remote file// const workbookData = await univerAPI.importSheetToSnapshotAsync('https://example.com/report.csv');if (workbookData) {  univerAPI.createWorkbook(workbookData)}

Types: IWorkbookData · Promise · File

Package: @univerjs-pro/sheets-exchange-client · Type definitions

FUniver.importSheetToUnitIdAsync

Import an XLSX, XLS, CSV, or TSV file into a persisted Sheet unit.

TypeScript
importSheetToUnitIdAsync(file: File | string): Promise<string | undefined>

Parameters

  • file — Required. File object or URL of the file to import

Returns

A promise that resolves to the imported unit ID, or undefined when the import does not produce a unit

Examples

TypeScript
// Accepts a File objectconst unitId = await univerAPI.importSheetToUnitIdAsync(file)// Or accepts a URL to a remote file// const unitId = await univerAPI.importSheetToUnitIdAsync('https://example.com/budget.xlsx');if (unitId) {  console.log('Imported Sheet unit:', unitId)}

Types: Promise · File

Package: @univerjs-pro/sheets-exchange-client · Type definitions

FUniver.transformSnapshotJsonToWorkbookDataAsync

Convert Sheet snapshot JSON returned by the exchange service into workbook data.

TypeScript
transformSnapshotJsonToWorkbookDataAsync(json: ISnapshotBlockJsonResponse): Promise<IWorkbookData>

Parameters

  • json — Required. Snapshot JSON and Sheet blocks returned by the exchange service

Returns

A promise that resolves to workbook data that can be passed to createWorkbook

Examples

TypeScript
import type { ISnapshotBlockJsonResponse } from '@univerjs-pro/exchange-client'const response = await fetch('/api/sheet-snapshot')const snapshotJson = (await response.json()) as ISnapshotBlockJsonResponseconst workbookData = await univerAPI.transformSnapshotJsonToWorkbookDataAsync(snapshotJson)univerAPI.createWorkbook(workbookData)

Types: IWorkbookData · Promise · ISnapshotBlockJsonResponse

Package: @univerjs-pro/sheets-exchange-client · Type definitions

FUniver.transformWorkbookDataToSnapshotJsonAsync

Convert workbook data into snapshot JSON accepted by the exchange service.

TypeScript
transformWorkbookDataToSnapshotJsonAsync(workbookData: IWorkbookData): Promise<ISnapshotBlockJson>

Parameters

  • workbookData — Required. Workbook data to convert

Returns

A promise that resolves to Snapshot JSON containing the workbook metadata and encoded Sheet blocks

Examples

TypeScript
const workbook = univerAPI.getActiveWorkbook()if (workbook) {  const workbookData = workbook.save()  const snapshotJson = await univerAPI.transformWorkbookDataToSnapshotJsonAsync(workbookData)  console.log('Sheet snapshot JSON:', snapshotJson)}

Types: ISnapshotBlockJson · Promise · IWorkbookData

Package: @univerjs-pro/sheets-exchange-client · Type definitions

@univerjs-pro/sheets-pivot

FUniver.generatePivotTable

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

TypeScript
generatePivotTable<T extends DataFieldManager>(data: IDataFieldDataArray, CustomDataFieldManager?: new (...args: unknown[]) => T): FGenericPivotTable

Parameters

  • data — Required. The data used to create the pivot table
  • CustomDataFieldManager — Optional. The custom data field manager class. If not passed, the default DataFieldManager will be used

Returns

The generated pivot table instance.

Examples

TypeScript
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)

Types: FGenericPivotTable · IDataFieldDataArray

Package: @univerjs-pro/sheets-pivot · Type definitions

@univerjs-pro/slides

FUniver.createPresentation

Creates a new presentation unit.

TypeScript
createPresentation(data?: Partial<ISlideData>, options?: ICreateUnitOptions): FPresentation

Parameters

  • data — Optional. Default: {}. The initial presentation snapshot data.
  • options — Optional. The unit creation options.

Returns

The created presentation facade.

Examples

TypeScript
const fPresentation = univerAPI.createPresentation({  id: 'presentation-1',  name: 'Quarterly Review',})console.log(fPresentation)

Types: FPresentation · Partial · ISlideData · ICreateUnitOptions

Package: @univerjs-pro/slides · Type definitions

FUniver.getActivePresentation

Get the active presentation.

TypeScript
getActivePresentation(): FPresentation | null

Returns

The active presentation, or null if no presentation is active.

Examples

TypeScript
const fPresentation = univerAPI.getActivePresentation()console.log(fPresentation)

Types: FPresentation

Package: @univerjs-pro/slides · Type definitions

FUniver.getPresentation

Get a presentation by id.

TypeScript
getPresentation(id: string): FPresentation | null

Parameters

  • id — Required. The presentation id.

Returns

The presentation, or null if it does not exist.

Examples

TypeScript
const fPresentation = univerAPI.getPresentation('presentation-1')console.log(fPresentation)

Types: FPresentation

Package: @univerjs-pro/slides · Type definitions

FUniver.getSlideCommandTarget

Resolve the presentation and slide target from command params.

TypeScript
getSlideCommandTarget(params?: { unitId?: string; subUnitId?: string; slideId?: string; }): { presentation: FPresentation; slide: FSlide; unitId: string; subUnitId: string; } | null

Parameters

  • params — Optional. Default: {}. The command params containing unitId, subUnitId, or slideId.

Returns

The resolved presentation, slide, unit id, and sub unit id, or null.

Examples

TypeScript
univerAPI.addEvent(univerAPI.Event.CommandExecuted, (commandInfo) => {  const target = univerAPI.getSlideCommandTarget(commandInfo.params)  console.log(target)})

Types: FPresentation · FSlide

Package: @univerjs-pro/slides · Type definitions

@univerjs-pro/slides-exchange-client

FUniver.exportSlideBySnapshotAsync

Export Slide snapshot data as a PPTX file.

TypeScript
exportSlideBySnapshotAsync(snapshot: ISlideData): Promise<File | undefined>

Parameters

  • snapshot — Required. Slide data to export

Returns

A promise that resolves to the exported PPTX file, or undefined when the export does not produce a file

Examples

TypeScript
const presentation = univerAPI.getActivePresentation()if (presentation) {  const file = await univerAPI.exportSlideBySnapshotAsync(presentation.save())  if (file) {    univerAPI.downloadFile(file, 'presentation', 'pptx')  }}

Types: File · Promise · ISlideData

Package: @univerjs-pro/slides-exchange-client · Type definitions

FUniver.exportSlideByUnitIdAsync

Export a persisted Slide unit as a PPTX file.

TypeScript
exportSlideByUnitIdAsync(unitId: string): Promise<File | undefined>

Parameters

  • unitId — Required. ID of the Slide unit to export

Returns

A promise that resolves to the exported PPTX file, or undefined when the export does not produce a file

Examples

TypeScript
const file = await univerAPI.exportSlideByUnitIdAsync(unitId)if (file) {  univerAPI.downloadFile(file, 'presentation', 'pptx')}

Types: File · Promise

Package: @univerjs-pro/slides-exchange-client · Type definitions

FUniver.importSlideToSnapshotAsync

Import a PPTX file into Slide snapshot data.

TypeScript
importSlideToSnapshotAsync(file: File | string): Promise<ISlideData | undefined>

Parameters

  • file — Required. File object or URL of the PPTX file to import

Returns

A promise that resolves to Slide data, or undefined when the import does not produce a snapshot

Examples

TypeScript
// Accepts a File objectconst slideData = await univerAPI.importSlideToSnapshotAsync(file)// Or accepts a URL to a remote file// const slideData = await univerAPI.importSlideToSnapshotAsync('https://example.com/presentation.pptx');

Types: ISlideData · Promise · File

Package: @univerjs-pro/slides-exchange-client · Type definitions

FUniver.importSlideToUnitIdAsync

Import a PPTX file into a persisted Slide unit.

TypeScript
importSlideToUnitIdAsync(file: File | string): Promise<string | undefined>

Parameters

  • file — Required. File object or URL of the PPTX file to import

Returns

A promise that resolves to the imported unit ID, or undefined when the import does not produce a unit

Examples

TypeScript
// Accepts a File objectconst unitId = await univerAPI.importSlideToUnitIdAsync(file)// Or accepts a URL to a remote file// const unitId = await univerAPI.importSlideToUnitIdAsync('https://example.com/presentation.pptx');

Types: Promise · File

Package: @univerjs-pro/slides-exchange-client · Type definitions

FUniver.transformSlideDataToSnapshotJsonAsync

Convert Slide data into snapshot JSON accepted by the exchange service.

TypeScript
transformSlideDataToSnapshotJsonAsync(slideData: ISlideData): Promise<ISnapshotBlockJson>

Parameters

  • slideData — Required. Slide data to convert

Returns

A promise that resolves to encoded Snapshot JSON

Examples

TypeScript
const presentation = univerAPI.getActivePresentation()if (presentation) {  const snapshotJson = await univerAPI.transformSlideDataToSnapshotJsonAsync(presentation.save())}

Types: ISnapshotBlockJson · Promise · ISlideData

Package: @univerjs-pro/slides-exchange-client · Type definitions

FUniver.transformSnapshotJsonToSlideDataAsync

Convert Slide snapshot JSON returned by the exchange service into Slide data.

TypeScript
transformSnapshotJsonToSlideDataAsync(json: ISnapshotBlockJsonResponse): Promise<ISlideData>

Parameters

  • json — Required. Snapshot JSON returned by the exchange service

Returns

A promise that resolves to Slide data

Examples

TypeScript
const slideData = await univerAPI.transformSnapshotJsonToSlideDataAsync(snapshotJson)

Types: ISlideData · Promise · ISnapshotBlockJsonResponse

Package: @univerjs-pro/slides-exchange-client · Type definitions

@univerjs-pro/slides-print

FUniver.openSlidesPrintDialog

Open the Univer Slides print settings and preview.

TypeScript
openSlidesPrintDialog(options?: ISlidePrintOptions): boolean

Parameters

  • options — Optional.

Types: ISlidePrintOptions

Package: @univerjs-pro/slides-print · Type definitions

FUniver.printSlidesAsync

Open the browser print dialog for the active presentation.

TypeScript
printSlidesAsync(options?: ISlidePrintOptions): Promise<boolean>

Parameters

  • options — Optional. Optional print options. range accepts 1-based page ranges. Overlapping ranges are de-duped and printed in the original slide order.

Returns

Whether the print operation was started.

Examples

TypeScript
await univerAPI.printSlidesAsync()await univerAPI.printSlidesAsync({  range: [{ from: 1, to: 3 }],  layout: univerAPI.Enum.SlidePrintLayoutType.Handout,  slidesPerPage: 6,  handoutOrder: univerAPI.Enum.SlidePrintHandoutOrder.Horizontal,  frameSlides: true,  showSlideNumber: true,})

Types: Promise · ISlidePrintOptions

Package: @univerjs-pro/slides-print · Type definitions

How is this guide?

© 2026 DreamNum Co., Ltd.