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
addEvent<T extends keyof IEventParamConfig>(event: T, callback: (params: IEventParamConfig[T]) => void): IDisposableParameters
event— Required. key of eventcallback— Required. callback when event triggered
Returns
A disposable that removes the event listener.
Examples
// 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.
disposeUnit(unitId: string): booleanParameters
unitId— Required. The ID of the unit to dispose.
Returns
Whether the Univer instance is disposed successfully.
Examples
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.
readonly Enum: FEnumTypes: FEnum
Package: @univerjs/core · Type definitions
FUniver.Event
Event names to use with addEvent.
readonly Event: FEventNameTypes: FEventName
Package: @univerjs/core · Type definitions
FUniver.executeCommand
Execute a command with the given id and parameters.
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
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.
getCurrentLifecycleStage(): LifecycleStagesReturns
- The current lifecycle stage.
Examples
const stage = univerAPI.getCurrentLifecycleStage()console.log(stage)Types: LifecycleStages
Package: @univerjs/core · Type definitions
FUniver.getCurrentLocale
Get the current locale.
getCurrentLocale(): stringReturns
The current locale identifier.
Examples
const currentLocale = univerAPI.getCurrentLocale()console.log(currentLocale)Package: @univerjs/core · Type definitions
FUniver.getCurrentRegion
Get the region currently used for locale-sensitive formatting.
getCurrentRegion(): stringReturns
The current region identifier.
Examples
const currentRegion = univerAPI.getCurrentRegion()console.log(currentRegion)Package: @univerjs/core · Type definitions
FUniver.getCurrentTheme
Get the theme currently used by Univer.
getCurrentTheme(): ThemeReturns
The current theme.
Examples
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.
getLocales(): ILanguagePack | undefinedReturns
The locales object for the current locale, it returns undefined if the locales is not loaded.
Examples
const locales = univerAPI.getLocales()console.log(locales)Types: ILanguagePack
Package: @univerjs/core · Type definitions
FUniver.getUserManager
Gets the facade for reading the current user.
getUserManager(): FUserManagerReturns
The user manager facade.
Examples
const user = univerAPI.getUserManager().getCurrentUser()Types: FUserManager
Package: @univerjs/core · Type definitions
FUniver.isDarkMode
Whether Univer is currently using dark mode.
isDarkMode(): booleanReturns
Whether dark mode is enabled.
Examples
const darkMode = univerAPI.isDarkMode()Package: @univerjs/core · Type definitions
FUniver.loadLocales
Load locales for the given locale.
loadLocales(locale: string, locales: ILanguagePack): voidParameters
locale— Required. A unique locale identifier.locales— Required. The locales object containing the translations.
Examples
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.
static newAPI(wrapped: Univer | Injector): FUniverParameters
wrapped— Required. The Univer instance or injector instance.
Returns
- The FUniver instance.
Examples
const univerAPI = FUniver.newAPI(univer)Types: FUniver · Univer · Injector
Package: @univerjs/core · Type definitions
FUniver.newBlob
Create a new blob.
newBlob(): FBlobReturns
The new blob instance
Examples
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({ ... }).
newParagraphStyle(style?: IParagraphStyle): ParagraphStyleBuilderParameters
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.
newParagraphStyleValue(style?: IParagraphStyle): ParagraphStyleValueParameters
style— Optional. The paragraph style
Returns
The new paragraph style value instance
Examples
const paragraphStyleValue = univerAPI.newParagraphStyleValue()Types: ParagraphStyleValue · IParagraphStyle
Package: @univerjs/core · Type definitions
FUniver.newRichText
Create a new rich text.
newRichText(): RichTextBuilderReturns
The new rich text instance
Examples
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().
newRichTextFromDocumentData(data: IDocumentData): RichTextBuilderParameters
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().
newRichTextValue(data: IDocumentData): RichTextValueParameters
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.
newTextDecoration(decoration?: ITextDecoration): TextDecorationBuilderParameters
decoration— Optional. The text decoration
Returns
The new text decoration instance
Examples
const decoration = univerAPI.newTextDecoration()Types: TextDecorationBuilder · ITextDecoration
Package: @univerjs/core · Type definitions
FUniver.newTextStyle
Create a new text style.
newTextStyle(style?: ITextStyle): TextStyleBuilderParameters
style— Optional. The text style
Returns
The new text style instance
Examples
const textStyle = univerAPI.newTextStyle()Types: TextStyleBuilder · ITextStyle
Package: @univerjs/core · Type definitions
FUniver.newTextStyleValue
Create a new text style value.
newTextStyleValue(style?: ITextStyle): TextStyleValueParameters
style— Optional. The text style
Returns
The new text style value instance
Examples
const textStyleValue = univerAPI.newTextStyleValue()Types: TextStyleValue · ITextStyle
Package: @univerjs/core · Type definitions
FUniver.redo
Redo an editing on the currently focused document.
redo(): Promise<boolean>Returns
redo result
Examples
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.
registerEventHandler: (event: string, handler: () => IDisposable | Subscription) => IDisposableReturns
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.
setDirection(direction: 'ltr' | 'rtl'): voidParameters
direction— Required. The layout direction.
Examples
univerAPI.setDirection('rtl')Package: @univerjs/core · Type definitions
FUniver.setLocale
Set the current locale.
setLocale(locale: string): voidParameters
locale— Required. A unique locale identifier.
Examples
univerAPI.setLocale('esES')Package: @univerjs/core · Type definitions
FUniver.setRegion
Set the region used for locale-sensitive formatting.
setRegion(region: string): voidParameters
region— Required. A unique region identifier.
Examples
univerAPI.setRegion('enUS')Package: @univerjs/core · Type definitions
FUniver.setTheme
Set the theme used by Univer.
setTheme(theme: Theme): voidParameters
theme— Required. The complete theme to use.
Examples
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.
syncExecuteCommand<P extends object = object, R = boolean>(id: string, params?: P, options?: IExecutionOptions): RParameters
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
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.
toggleDarkMode(isDarkMode: boolean): voidParameters
isDarkMode— Required. Whether the dark mode is enabled.
Examples
univerAPI.toggleDarkMode(true)Package: @univerjs/core · Type definitions
FUniver.undo
Undo an editing on the currently focused document.
undo(): Promise<boolean>Returns
undo result
Examples
await univerAPI.undo()Types: Promise
Package: @univerjs/core · Type definitions
FUniver.Util
Utility functions exposed by the registered Facade extensions.
readonly Util: FUtilTypes: FUtil
Package: @univerjs/core · Type definitions
@univerjs/docs
FUniver.createDocument
Create a new document and get the API handler of that document.
createDocument(data: Partial<IDocumentData>, options?: ICreateUnitOptions): FDocumentParameters
data— Required. The snapshot of the document.options— Optional. The options of creating the document.
Returns
The document API instance.
Examples
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.
getActiveDocument(): FDocument | nullReturns
The currently focused Univer document API instance, or null if there is no focused Univer document.
Examples
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.
getDocument(id: string): FDocument | nullParameters
id— Required. The document id.
Returns
The document API instance corresponding to the document id, or null if not found.
Examples
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.
getFormula(): FFormulaReturns
The formula engine facade.
Examples
const formula = univerAPI.getFormula()await formula.onCalculationResultApplied()Types: FFormula
Package: @univerjs/engine-formula · Type definitions
@univerjs/network
FUniver.createSocket
Set WebSocket URL for WebSocketService
createSocket(url: string): ISocketParameters
url— Required. WebSocket URL
Returns
WebSocket instance
Examples
// 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.
getNetwork(): FNetworkTypes: FNetwork
Package: @univerjs/network · Type definitions
@univerjs/sheets
FUniver.createWorkbook
Create a new spreadsheet and get the API handler of that spreadsheet.
createWorkbook(data: Partial<IWorkbookData>, options?: ICreateUnitOptions): FWorkbookParameters
data— Required. The snapshot of the spreadsheet.options— Optional. The options of creating the spreadsheet.
Returns
The spreadsheet API instance.
Examples
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:
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.
getActiveSheet(): { workbook: FWorkbook; worksheet: FWorksheet; } | nullReturns
The active sheet.
Examples
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.
getActiveWorkbook(): FWorkbook | nullReturns
The currently focused Univer spreadsheet API instance, or null if there is no active spreadsheet.
Examples
const fWorkbook = univerAPI.getActiveWorkbook()console.log(fWorkbook)Types: FWorkbook
Package: @univerjs/sheets · Type definitions
FUniver.getSheetCommandTarget
Get the target of the sheet.
getSheetCommandTarget(params?: { unitId?: string; subUnitId?: string; sheetId?: string; }): { workbook: FWorkbook; worksheet: FWorksheet; unitId: string; subUnitId: string; } | nullParameters
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
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.
getWorkbook(id: string): FWorkbook | nullParameters
id— Required. The spreadsheet id.
Returns
The spreadsheet API instance corresponding to the spreadsheet id, or null if not found.
Examples
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.
setFreezeSync(enabled: boolean): voidParameters
enabled— Required. Whether to enable freeze sync. Default is true.
Examples
// Disable freeze syncuniverAPI.setFreezeSync(false)Package: @univerjs/sheets · Type definitions
@univerjs/sheets-crosshair-highlight
FUniver.getCrosshairHighlightEnabled
Get whether the crosshair highlight is enabled.
getCrosshairHighlightEnabled(): booleanReturns
Whether the crosshair highlight is enabled
Examples
console.log(univerAPI.getCrosshairHighlightEnabled())Package: @univerjs/sheets-crosshair-highlight · Type definitions
FUniver.setCrosshairHighlightEnabled
Enable or disable crosshair highlight.
setCrosshairHighlightEnabled(enabled: boolean): FUniverParameters
enabled— Required. Whether to enable the crosshair highlight
Returns
The FUniver instance for chaining
Examples
univerAPI.setCrosshairHighlightEnabled(true)Types: FUniver
Package: @univerjs/sheets-crosshair-highlight · Type definitions
@univerjs/sheets-data-validation
FUniver.newDataValidation
Creates a new instance of FDataValidationBuilder
newDataValidation(): FDataValidationBuilderReturns
A new instance of the FDataValidationBuilder class
Examples
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
registerURLImageDownloader(downloader: (url: string) => Promise<string>): IDisposableParameters
downloader— Required. The downloader function that takes a URL and returns a base64 string
Returns
A disposable object to unregister the downloader
Examples
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.
createTextFinderAsync(text: string): Promise<FTextFinder | null>Parameters
text— Required. The text to find.
Returns
A promise that resolves to the text-finder instance.
Examples
// 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.
showRangeSelectorDialog(opts: IShowRangeSelectorDialogOptions): Promise<IUnitRangeName[]>Parameters
opts— Required. The options of the range selector dialog.
Returns
The selected ranges.
Examples
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.
getProtectedRangeShadowStrategy(): 'always' | 'non-editable' | 'non-viewable' | 'none'Returns
The current shadow strategy
Examples
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.
getProtectedRangeShadowStrategy$(): Observable<'always' | 'non-editable' | 'non-viewable' | 'none'>Returns
An observable that emits the current shadow strategy
Examples
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.
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
// 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')Package: @univerjs/sheets-ui · Type definitions
FUniver.registerCellCustomRender
Register cell custom render.
registerCellCustomRender(customRender: Nullable<ICellCustomRender[]>, effect?: InterceptorEffectEnum, priority?: number): IDisposableParameters
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.
registerSheetColumnHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposableParameters
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.
registerSheetMainExtension(unitId: string, ...extensions: SheetExtension[]): IDisposableParameters
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.
registerSheetRowHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposableParameters
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
setPermissionDialogVisible(visible: boolean): voidParameters
visible— Required. visibility of unauthorized pop-up window
Examples
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.
setProtectedRangeShadowStrategy(strategy: 'always' | 'non-editable' | 'non-viewable' | 'none'): voidParameters
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
// 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.
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
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.
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
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.
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
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.
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
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.
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
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.
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
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.
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
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.
addFonts(fonts: IFontConfig[]): voidParameters
fonts— Required. The array of font configurations to add.
Examples
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.
copy(): Promise<boolean>Returns
whether the copy operation is successful
Examples
// 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.
createMenu(menuItem: IFacadeMenuItem): FMenuParameters
menuItem— Required. the menu item
Returns
the FMenu object
Examples
// 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.
createSubmenu(submenuItem: IFacadeSubmenuItem): FSubmenuParameters
submenuItem— Required. the submenu item
Returns
the FSubmenu object
Examples
// 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
getComponentManager(): ComponentManagerReturns
The component manager
Examples
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.
getShortcut(): FShortcutReturns
the FShortcut object
Examples
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.
getURL(): URLReturns
the URL object
Examples
console.log(univerAPI.getURL())Types: URL
Package: @univerjs/ui · Type definitions
FUniver.isUIVisible
Get the visibility of a built-in UI part.
isUIVisible(ui: BuiltInUIPart): booleanParameters
ui— Required.
Returns
the visibility
Examples
// Hide headeruniverAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false)console.log(univerAPI.isUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER)) // falseTypes: BuiltInUIPart
Package: @univerjs/ui · Type definitions
FUniver.openDialog
Open a dialog.
openDialog(dialog: IDialogPartMethodOptions): IDisposableParameters
dialog— Required. the dialog options
Returns
the disposable object
Examples
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.
openSidebar(params: ISidebarMethodOptions): IDisposableParameters
params— Required. the sidebar options
Returns
the disposable object
Examples
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.
paste(): Promise<boolean>Returns
whether the paste operation is successful
Examples
// 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.
registerComponent(name: string, component: ComponentType, options?: IComponentOptions): IDisposableParameters
name— Required. The name of the component.component— Required. The component.options— Optional. The options of the component.
Returns
The disposable object.
Examples
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
registerUIPart(key: BuiltInUIPart, component: ComponentType): IDisposableParameters
key— Required. the built-in UI partcomponent— Required. the react component
Examples
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.
setCurrent(unitId: string): voidParameters
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.
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.
setRibbonType(ribbonType: RibbonType): FUniverParameters
ribbonType— Required. The ribbon layout type.
Returns
the FUniver instance for chaining
Examples
univerAPI.setRibbonType('grid')Types: FUniver · RibbonType
Package: @univerjs/ui · Type definitions
FUniver.setUIVisible
Set the visibility of a built-in UI part.
setUIVisible(ui: BuiltInUIPart, visible: boolean): FUniverParameters
ui— Required.visible— Required. the visibility
Returns
the FUniver instance for chaining
Examples
// 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.
showMessage(options: IMessageProps): FUniverParameters
options— Required. Message content, type, duration, and other display options.
Returns
the FUniver instance for chaining
Examples
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.
updateMenuConfig(config: MenuConfig): FUniverParameters
config— Required. Overrides keyed by menu item ID, ribbon tab key, or ribbon group key. Unspecified properties keep their current values. Lowerordervalues come first among siblings.gridLayoutapplies only to the grid ribbon and uses 1-based positions within a two-row group.
Returns
the FUniver instance for chaining
Examples
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.
addWatermark(type: IWatermarkTypeEnum.Text, config: ITextWatermarkConfig): FUniveraddWatermark(type: IWatermarkTypeEnum.Image, config: IImageWatermarkConfig): FUniverParameters
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
univerAPI.addWatermark('text', { content: 'Univer', fontSize: 20, repeat: true,})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.
deleteWatermark(): FUniverReturns
The FUniver instance for chaining.
Examples
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.
createBase(snapshot?: Partial<IBaseSnapshot>, options?: ICreateUnitOptions): FBaseParameters
snapshot— Optional. Default:{}. The persisted Base model snapshot.options— Optional. Options for creating the unit.
Returns
The Base facade API instance.
Examples
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.
getActiveBase(): FBase | nullReturns
The active Base facade, or null if no Base is active.
Examples
const fBase = univerAPI.getActiveBase()console.log(fBase)Types: FBase
Package: @univerjs-pro/bases · Type definitions
FUniver.getBase
Get a Base unit by id.
getBase(baseId: string): FBase | nullParameters
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
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.
getBases(): FBase[]Returns
An array of Base facade instances.
Examples
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.
exportBaseBySnapshotAsync(snapshot: IBaseSnapshot, format?: ExchangeFormat, tableId?: string): Promise<File | undefined>Parameters
snapshot— Required. Base data to exportformat— Optional. Output formattableId— 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
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.
exportBaseByUnitIdAsync(unitId: string, format?: ExchangeFormat, tableId?: string): Promise<File | undefined>Parameters
unitId— Required. ID of the Base unit to exportformat— Optional. Output formattableId— 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
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.
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
// 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.
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
// 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');Package: @univerjs-pro/bases-exchange-client · Type definitions
FUniver.transformBaseDataToSnapshotJsonAsync
Convert Base data into snapshot JSON accepted by the exchange service.
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
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.
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
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.
getBaseUI(): FBaseUITypes: FBaseUI
Package: @univerjs-pro/bases-ui · Type definitions
@univerjs-pro/boards
FUniver.createBoard
Creates a board unit and returns its facade.
createBoard(data?: Partial<IBoardData>, options?: ICreateUnitOptions): FBoardParameters
data— Optional. Default:{}. Optional board snapshot fields such asname.options— Optional. Optional Univer unit creation options.
Returns
A board facade for the created unit.
Examples
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.
getActiveBoard(): FBoard | nullReturns
The active board facade, or null when the current Univer unit is not a board.
Examples
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.
getBoard(id: string): FBoard | nullParameters
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
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.
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
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.
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
const file = await univerAPI.exportBoardByUnitIdAsync(unitId)if (file) { univerAPI.downloadFile(file, 'board', 'pptx')}Package: @univerjs-pro/boards-exchange-client · Type definitions
FUniver.transformBoardDataToSnapshotJsonAsync
Convert Board data into snapshot JSON accepted by the exchange service.
transformBoardDataToSnapshotJsonAsync(boardData: IBoardData): Promise<ISnapshotBlockJson>Parameters
boardData— Required. Board data to convert
Returns
A promise that resolves to encoded Snapshot JSON
Examples
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.
transformSnapshotJsonToBoardDataAsync(json: ISnapshotBlockJsonResponse): Promise<IBoardData>Parameters
json— Required. Snapshot JSON returned by the exchange service
Returns
A promise that resolves to Board data
Examples
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.
getCollaboration(): FCollaborationReturns
The collaboration instance.
Examples
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.
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
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.
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
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.
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 runparams— 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.
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
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.
exportDocByUnitIdAsync(unitId: string): Promise<File | undefined>Parameters
unitId— Required. Document unit ID
Returns
A promise that resolves to the DOCX file, or undefined
Examples
const file = await univerAPI.exportDocByUnitIdAsync(unitId)if (file) univerAPI.downloadFile(file, 'document', 'docx')Package: @univerjs-pro/docs-exchange-client · Type definitions
FUniver.importDocToSnapshotAsync
Import a DOCX file into Document snapshot data.
importDocToSnapshotAsync(file: File | string, options?: IExchangeDocImportOption): Promise<IDocumentData | undefined>Parameters
file— Required. File object or URL of the DOCX file to importoptions— Optional. Document type to use for the imported document
Returns
A promise that resolves to Document data, or undefined
Examples
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.
importDocToUnitIdAsync(file: File | string, options?: IExchangeDocImportOption): Promise<string | undefined>Parameters
file— Required. File object or URL of the DOCX file to importoptions— Optional. Document type to use for the imported document
Returns
A promise that resolves to the imported unit ID, or undefined
Examples
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.
transformDocumentDataToSnapshotJsonAsync(documentData: IDocumentData): Promise<ISnapshotBlockJson>Parameters
documentData— Required. Document data to convert
Returns
A promise that resolves to Snapshot JSON
Examples
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.
transformSnapshotJsonToDocumentDataAsync(json: ISnapshotBlockJsonResponse): Promise<IDocumentData>Parameters
json— Required. Snapshot JSON returned by the exchange service
Returns
A promise that resolves to Document data
Examples
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.
compareUnitData(input: IUnitComparisonInput): IUnitComparisonResultParameters
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.
prepareUnitComparison(input: Omit<IUnitComparisonInput, 'query'>): FUnitComparisonParameters
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.
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
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
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
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.
getEmbed(params: IGetEmbedParams): FEmbed<unknown> | nullParameters
params— Required. Get parameters.
Returns
The embed facade, or null when it does not exist.
Examples
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.
listEmbeds(params?: IListEmbedsParams): Array<FEmbed<unknown>>Parameters
params— Optional. Default:{}. List parameters.
Returns
Active embed facades.
Examples
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.
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
const document = await univerAPI.loadUnitAsync<UniverFacadeTypes.FDocument>( '#unit=another-unit-id&type=doc', { unitType: univerAPI.Enum.UniverInstanceType.UNIVER_DOC },)JavaScript
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.
removeEmbed(params: IRemoveEmbedParams): booleanParameters
params— Required. Remove parameters.
Returns
true when the remove command succeeds.
Examples
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.
registerTheme(name: string, theme: IEchartTheme): voidParameters
name— Required. The stable name used by Chart builders.theme— Required. The complete Chart theme definition.
Examples
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.
downloadFile(file: File | Blob, filename: string, fileExt: string): voidParameters
file— Required. File or blob to downloadfilename— Required. Filename without extensionfileExt— Required. File extension without a leading dot
Examples
const file = await univerAPI.exportSheetByUnitIdAsync(unitId)if (file) univerAPI.downloadFile(file, 'univer', 'xlsx')Package: @univerjs-pro/exchange-client · Type definitions
@univerjs-pro/pdfs
FUniver.createPdf
Create a PDF unit and return its Facade.
createPdf(data?: Partial<IPdfUnitData>, options?: ICreateUnitOptions): FPdfParameters
data— Optional. Default:{}. The PDF Unit data. Assign an existing PDF document todata.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
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.
getActivePdf(): FPdf | nullReturns
The active PDF Facade, or null when no PDF is active.
Examples
const pdf = univerAPI.getActivePdf()console.log(pdf?.getName())Types: FPdf
Package: @univerjs-pro/pdfs · Type definitions
FUniver.getPdf
Return a PDF unit by ID.
getPdf(id: string): FPdf | nullParameters
id— Required. The PDF unit ID.
Returns
The matching PDF Facade, or null when it does not exist.
Examples
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.
getPdfTableThemePresets(): ReadonlyArray<Readonly<IPdfTableThemePreset>>Returns
Detached preset descriptors.
Examples
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.
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
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.
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
const file = await univerAPI.exportPdfByUnitIdAsync(unitId)if (file) { univerAPI.downloadFile(file, 'document', 'pdf')}Package: @univerjs-pro/pdfs-exchange-client · Type definitions
FUniver.importPdfToSnapshotAsync
Import a PDF file into PDF snapshot data.
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
// 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.
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
// 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');Package: @univerjs-pro/pdfs-exchange-client · Type definitions
FUniver.transformPdfDataToSnapshotJsonAsync
Convert PDF data into snapshot JSON accepted by the exchange service.
transformPdfDataToSnapshotJsonAsync(pdfData: IPdfUnitData): Promise<ISnapshotBlockJson>Parameters
pdfData— Required. PDF data to convert
Returns
A promise that resolves to encoded Snapshot JSON
Examples
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.
transformSnapshotJsonToPdfDataAsync(json: ISnapshotBlockJsonResponse): Promise<IPdfUnitData>Parameters
json— Required. Snapshot JSON returned by the exchange service
Returns
A promise that resolves to PDF data
Examples
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.
exportSheetBySnapshotAsync(snapshot: IWorkbookData, format?: ExchangeFormat, sheetId?: string): Promise<File | undefined>Parameters
snapshot— Required. Workbook data to exportformat— Optional. Output formatsheetId— 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
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.
exportSheetByUnitIdAsync(unitId: string, format?: ExchangeFormat, sheetId?: string): Promise<File | undefined>Parameters
unitId— Required. ID of the Sheet unit to exportformat— Optional. Output formatsheetId— 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
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.
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
// 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.
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
// 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)}Package: @univerjs-pro/sheets-exchange-client · Type definitions
FUniver.transformSnapshotJsonToWorkbookDataAsync
Convert Sheet snapshot JSON returned by the exchange service into workbook data.
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
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.
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
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
generatePivotTable<T extends DataFieldManager>(data: IDataFieldDataArray, CustomDataFieldManager?: new (...args: unknown[]) => T): FGenericPivotTableParameters
data— Required. The data used to create the pivot tableCustomDataFieldManager— Optional. The custom data field manager class. If not passed, the default DataFieldManager will be used
Returns
The generated pivot table instance.
Examples
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.
createPresentation(data?: Partial<ISlideData>, options?: ICreateUnitOptions): FPresentationParameters
data— Optional. Default:{}. The initial presentation snapshot data.options— Optional. The unit creation options.
Returns
The created presentation facade.
Examples
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.
getActivePresentation(): FPresentation | nullReturns
The active presentation, or null if no presentation is active.
Examples
const fPresentation = univerAPI.getActivePresentation()console.log(fPresentation)Types: FPresentation
Package: @univerjs-pro/slides · Type definitions
FUniver.getPresentation
Get a presentation by id.
getPresentation(id: string): FPresentation | nullParameters
id— Required. The presentation id.
Returns
The presentation, or null if it does not exist.
Examples
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.
getSlideCommandTarget(params?: { unitId?: string; subUnitId?: string; slideId?: string; }): { presentation: FPresentation; slide: FSlide; unitId: string; subUnitId: string; } | nullParameters
params— Optional. Default:{}. The command params containingunitId,subUnitId, orslideId.
Returns
The resolved presentation, slide, unit id, and sub unit id, or null.
Examples
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.
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
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.
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
const file = await univerAPI.exportSlideByUnitIdAsync(unitId)if (file) { univerAPI.downloadFile(file, 'presentation', 'pptx')}Package: @univerjs-pro/slides-exchange-client · Type definitions
FUniver.importSlideToSnapshotAsync
Import a PPTX file into Slide snapshot data.
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
// 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.
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
// 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');Package: @univerjs-pro/slides-exchange-client · Type definitions
FUniver.transformSlideDataToSnapshotJsonAsync
Convert Slide data into snapshot JSON accepted by the exchange service.
transformSlideDataToSnapshotJsonAsync(slideData: ISlideData): Promise<ISnapshotBlockJson>Parameters
slideData— Required. Slide data to convert
Returns
A promise that resolves to encoded Snapshot JSON
Examples
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.
transformSnapshotJsonToSlideDataAsync(json: ISnapshotBlockJsonResponse): Promise<ISlideData>Parameters
json— Required. Snapshot JSON returned by the exchange service
Returns
A promise that resolves to Slide data
Examples
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.
openSlidesPrintDialog(options?: ISlidePrintOptions): booleanParameters
options— Optional.
Types: ISlidePrintOptions
Package: @univerjs-pro/slides-print · Type definitions
FUniver.printSlidesAsync
Open the browser print dialog for the active presentation.
printSlidesAsync(options?: ISlidePrintOptions): Promise<boolean>Parameters
options— Optional. Optional print options.rangeaccepts 1-based page ranges. Overlapping ranges are de-duped and printed in the original slide order.
Returns
Whether the print operation was started.
Examples
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?