Class: FUniver
The root Facade API object to interact with Univer. Please use newAPI static method
to create a new instance.
Extends
IFUniverNetworkMixin.IFUniverNetworkMixin.IFUniverEngineFormulaMixin.IFUniverSheetsMixin.IFUniverSheetsFormulaMixin.IFUnvierDataValidationMixin.IFUniverCommentMixin.IFUniverCollaborationClientMixin.IFUniverPivotTableEventMixin.IFUniverDocsUIMixin.IFUniverUIMixin.IFUniverSheetsUIMixin.IFUniverFindReplaceMixin.IFUniverCrosshairHighlightMixin.IFUniverWatermarkMixin.IFUniverSheetsZenEditorMixin.IFUniverNodeRuntimeMixin.IFUniverExchangeClientMixin
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
|
|
|
Get the available built-in colors for the crosshair highlight. | |
|
|
( |
‐ |
Accessors
Enum
Get Signature
get Enum(): FEnumReturns
Event
Get Signature
get Event(): FEventNameReturns
Util
Get Signature
get Util(): FUtilReturns
FUtil
Methods
addEvent()
addEvent<T>(event, callback): IDisposableAdd an event listener
Type Parameters
| Type Parameter |
|---|
T extends keyof IEventParamConfig |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | T | key of event |
callback | (params) => void | callback when event triggered |
Returns
IDisposable
The Disposable instance, for remove the listener
Example
// Add life cycle changed event listener
const disposable = univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, (params) => {
const { stage } = params;
console.log('life cycle changed', params);
});
// Remove the event listener, use `disposable.dispose()`addFonts()
addFonts(fonts): voidAppend custom fonts to the font list.
Parameters
| Parameter | Type | Description |
|---|---|---|
fonts | IFontConfig[] | The array of font configurations to add. |
Returns
void
Example
univerAPI.addFonts([
{
value: 'CustomFont1',
label: 'Custom Font 1',
category: 'sans-serif',
},
{
value: 'CustomFont2',
label: 'Custom Font 2',
category: 'serif',
},
]);addWatermark()
Call Signature
addWatermark(type, config): FUniverAdds a watermark to the unit. Supports both text and image watermarks based on the specified type.
Parameters
| Parameter | Type | Description |
|---|---|---|
type | Text | The type of watermark to add is Text. |
config | ITextWatermarkConfig | The configuration object for the text type watermark. |
Returns
FUniver
The FUniver instance for chaining.
Throws
Throws an error if the watermark type is unknown.
Example
univerAPI.addWatermark('text', {
content: 'Univer',
fontSize: 20,
repeat: true,
});Call Signature
addWatermark(type, config): FUniverAdds a watermark to the unit. Supports both text and image watermarks based on the specified type.
Parameters
| Parameter | Type | Description |
|---|---|---|
type | Image | The type of watermark to add is Image. |
config | IImageWatermarkConfig | The configuration object for the image type watermark. |
Returns
FUniver
The FUniver instance for chaining.
Throws
Throws an error if the watermark type is unknown.
Example
univerAPI.addWatermark('image', {
url: 'https://avatars.githubusercontent.com/u/61444807?s=48&v=4',
width: 100,
height: 100,
});Call Signature
addWatermark(type, config): FUniverParameters
| Parameter | Type |
|---|---|
type | any |
config | any |
Returns
FUniver
copy()
copy(): Promise<boolean>Copy the current selected content of the currently focused unit into your system clipboard.
Returns
Promise<boolean>
whether the copy operation is successful
Example
// Prevent failure due to loss of focus when executing copy and paste code in the console,
// this example listens for the cell click event and executes the copy and paste code.
univerAPI.addEvent(univerAPI.Event.CellClicked, async (params) => {
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
// Copy the range A1:B2 to the clipboard
const fRange = fWorksheet.getRange('A1:B2');
fRange.activate().setValues([
[1, 2],
[3, 4]
]);
await univerAPI.copy();
// Paste the copied content to the range C1:D2
const fRange2 = fWorksheet.getRange('C1');
fRange2.activate();
await univerAPI.paste();
// Check the pasted content
console.log(fWorksheet.getRange('C1:D2').getValues()); // [[1, 2], [3, 4]]
});createMenu()
createMenu(menuItem): FMenuCreate a menu build object. You can insert new menus into the UI.
Parameters
| Parameter | Type | Description |
|---|---|---|
menuItem | IFacadeMenuItem | the menu item |
Returns
the FMenu object
Example
// Univer Icon can be viewed at https://docs.univer.ai/icons
import { SmileIcon } from '@univerjs/icons'
// Create a custom menu with an univer icon
univerAPI.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 icon
univerAPI.registerComponent('custom-menu-icon', () => {
return <img src="https://avatars.githubusercontent.com/u/61444807?s=48&v=4" alt="" style={{ width: '16px', height: '16px' }} />;
});
univerAPI.createMenu({
id: 'custom-menu',
icon: 'custom-menu-icon',
title: 'Custom Menu',
tooltip: 'Custom Menu Tooltip',
action: () => {
console.log('Custom Menu Clicked');
},
}).appendTo('ribbon.start.others');
// Or
// Create a custom menu without an icon
univerAPI.createMenu({
id: 'custom-menu',
title: 'Custom Menu',
tooltip: 'Custom Menu Tooltip',
action: () => {
console.log('Custom Menu Clicked');
},
}).appendTo('ribbon.start.others');createSubmenu()
createSubmenu(submenuItem): FSubmenuCreate a menu that contains submenus, and later you can append this menu and its submenus to the UI.
Parameters
| Parameter | Type | Description |
|---|---|---|
submenuItem | IFacadeSubmenuItem | the submenu item |
Returns
the FSubmenu object
Example
// Create two leaf menus.
const menu1 = univerAPI.createMenu({
id: 'submenu-nested-1',
title: 'Item 1',
action: () => {
console.log('Item 1 clicked');
}
});
const menu2 = univerAPI.createMenu({
id: 'submenu-nested-2',
title: 'Item 2',
action: () => {
console.log('Item 2 clicked');
}
});
// Add the leaf menus to a submenu.
const submenu = univerAPI.createSubmenu({ id: 'submenu-nested', title: 'Nested Submenu' })
.addSubmenu(menu1)
.addSeparator()
.addSubmenu(menu2);
// Create a root submenu append to the `contextMenu.others` section.
univerAPI.createSubmenu({ id: 'custom-submenu', title: 'Custom Submenu' })
.addSubmenu(submenu)
.appendTo('contextMenu.others');createTextFinderAsync()
createTextFinderAsync(text): Promise<FTextFinder>Create a text-finder for the current univer.
Parameters
| Parameter | Type | Description |
|---|---|---|
text | string | The text to find. |
Returns
Promise<FTextFinder>
A promise that resolves to the text-finder instance.
Example
// Assume the current sheet is empty sheet.
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
// 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
});createUniverDoc()
createUniverDoc(data): FDocumentCreate a new document and get the API handler of that document.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | Partial<IDocumentData> | The snapshot of the document. |
Returns
FDocument API instance.
createUniverSheet()
createUniverSheet(data): FWorkbookParameters
| Parameter | Type |
|---|---|
data | Partial<IWorkbookData> |
Returns
Deprecated
use univerAPI.createWorkbook instead.
createWorkbook()
createWorkbook(data, options?): FWorkbookCreate a new spreadsheet and get the API handler of that spreadsheet.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | Partial<IWorkbookData> | The snapshot of the spreadsheet. |
options? | ICreateUnitOptions | The options of creating the spreadsheet. |
Returns
FWorkbook API instance.
Example
const fWorkbook = univerAPI.createWorkbook({ id: 'Sheet1', name: 'Sheet1' });
console.log(fWorkbook);Add you can make the workbook not as the active workbook by setting options:
const fWorkbook = univerAPI.createWorkbook({ id: 'Sheet1', name: 'Sheet1' }, { makeCurrent: false });
console.log(fWorkbook);customizeColumnHeader()
customizeColumnHeader(cfg): voidParameters
| Parameter | Type |
|---|---|
cfg | IColumnsHeaderCfgParam |
Returns
void
Deprecated
use same API in FWorkbook and FWorkSheet.
customizeRowHeader()
customizeRowHeader(cfg): voidParameters
| Parameter | Type |
|---|---|
cfg | IRowsHeaderCfgParam |
Returns
void
Deprecated
use same API in FWorkbook and FWorkSheet.
deleteWatermark()
deleteWatermark(): FUniverDeletes the currently applied watermark from the unit. This function retrieves the watermark service and invokes the method to remove any existing watermark configuration.
Returns
FUniver
The FUniver instance for chaining.
Example
univerAPI.deleteWatermark();disposeUnit()
disposeUnit(unitId): booleanDispose the UniverSheet by the unitId. The UniverSheet would be unload from the application.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | The unit id of the UniverSheet. |
Returns
boolean
Whether the Univer instance is disposed successfully.
Example
const fWorkbook = univerAPI.getActiveWorkbook();
const unitId = fWorkbook?.getId();
if (unitId) {
univerAPI.disposeUnit(unitId);
}executeCommand()
executeCommand<P, R>(
id,
params?,
options?): Promise<R>Execute a command with the given id and parameters.
Type Parameters
| Type Parameter | Default type |
|---|---|
P extends object | object |
R | boolean |
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Identifier of the command. |
params? | P | Parameters of this execution. |
options? | IExecutionOptions | Options of this execution. |
Returns
Promise<R>
The result of the execution. It is a boolean value by default which indicates the command is executed.
Example
univerAPI.executeCommand('sheet.command.set-range-values', {
value: { v: "Hello, Univer!" },
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 }
});exportDOCXBySnapshotAsync()
exportDOCXBySnapshotAsync(snapshot): Promise<File>Export DOCX file by snapshot
Parameters
| Parameter | Type | Description |
|---|---|---|
snapshot | IDocumentData | Document data |
Returns
Promise<File>
DOCX file
Example
const snapshot = univerAPI.getActiveDocument().save();
const file = await univerAPI.exportDOCXBySnapshotAsync(snapshot);
downloadFile(file, 'univer', 'docx');exportDOCXByUnitIdAsync()
exportDOCXByUnitIdAsync(unitId): Promise<File>Export DOCX file by unit id
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | Unit id |
Returns
Promise<File>
XLSX file
Example
const unitId = univerAPI.getActiveWorkbook().getId();
const file = await univerAPI.exportDOCXByUnitIdAsync(unitId);
downloadFile(file, 'univer', 'docx');exportXLSXBySnapshot()
exportXLSXBySnapshot(snapshot): Promise<File>Export XLSX file by workbook data
Parameters
| Parameter | Type | Description |
|---|---|---|
snapshot | IWorkbookData | Workbook data |
Returns
Promise<File>
XLSX file
Deprecated
Please use exportXLSXBySnapshotAsync instead.
exportXLSXBySnapshotAsync()
exportXLSXBySnapshotAsync(snapshot): Promise<File>Export XLSX file by workbook data
Parameters
| Parameter | Type | Description |
|---|---|---|
snapshot | IWorkbookData | Workbook data |
Returns
Promise<File>
A promise that resolves to the XLSX file
Example
import { downloadFile } from '@univerjs-pro/exchange-client';
const fWorkbook = univerAPI.getActiveWorkbook();
const snapshot = fWorkbook.save();
const file = await univerAPI.exportXLSXBySnapshotAsync(snapshot);
// or with server-side calculation enabled
// const file = await univerAPI.exportXLSXBySnapshotAsync(snapshot, { enableServerCalculation: true });
// Download the file
downloadFile(file, 'univer', 'xlsx');exportXLSXByUnitId()
exportXLSXByUnitId(unitId): Promise<File>Export XLSX file by unit id
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | Unit id |
Returns
Promise<File>
XLSX file
Deprecated
Please use exportXLSXByUnitIdAsync instead.
exportXLSXByUnitIdAsync()
exportXLSXByUnitIdAsync(unitId): Promise<File>Export XLSX file by unit id
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | Unit id |
Returns
Promise<File>
A promise that resolves to the XLSX file
Example
import { downloadFile } from '@univerjs-pro/exchange-client';
const fWorkbook = univerAPI.getActiveWorkbook();
const unitId = fWorkbook.getId();
const file = await univerAPI.exportXLSXByUnitIdAsync(unitId);
// or with server-side calculation enabled
// const file = await univerAPI.exportXLSXByUnitIdAsync(unitId, { enableServerCalculation: true });
// Download the file
downloadFile(file, 'univer', 'xlsx');fireEvent()
fireEvent<T>(event, params): booleanFire an event, used in internal only.
Type Parameters
| Type Parameter |
|---|
T extends keyof IEventParamConfig |
Parameters
| Parameter | Type | Description |
|---|---|---|
event | T | key of event |
params | IEventParamConfig[T] | params of event |
Returns
boolean
should cancel
Example
this.fireEvent(univerAPI.Event.LifeCycleChanged, params);generatePivotTable()
generatePivotTable<T>(data, CustomDataFieldManager?): FGenericPivotTableCreate a pivot table instance that does not depend on a workbook
Type Parameters
| Type Parameter |
|---|
T extends DataFieldManager |
Parameters
| Parameter | Type | Description |
|---|---|---|
data | […[], ...(...)[][]] | The data used to create the pivot table |
CustomDataFieldManager? | (…args) => T | The custom data field manager class. If not passed, the default DataFieldManager will be used |
Returns
The generated pivot table instance.
Example
const sourceData = [
["区域", "省份", "城市", "类别", "商品", "数量", "销售日期"],
["西部", "河南", "洛阳", "fruit", "葡萄", 38, "2021-06-30"],
["北部", "辽宁", "沈阳", "fruit", "葡萄", 45, "2023-08-31"]
]
const pivot = univerAPI.generatePivotTable(sourceData);
pivot.addFieldWithName('数量', 3);
const res = pivot.getResultByCalculate();
console.log('debugger', pivot, res);getActiveDocument()
getActiveDocument(): FDocumentGet the currently focused Univer document.
Returns
The currently focused Univer document.
getActiveSheet()
getActiveSheet(): Nullable<{
workbook: ...;
worksheet: ...;
}>Get the active sheet.
Returns
Nullable<{
workbook: …;
worksheet: …;
}>
The active sheet.
Example
const target = univerAPI.getActiveSheet();
if (!target) return;
const { workbook, worksheet } = target;
console.log(workbook, worksheet);getActiveUniverSheet()
getActiveUniverSheet(): FWorkbookReturns
Deprecated
use univerAPI.getActiveWorkbook instead
getActiveWorkbook()
getActiveWorkbook(): FWorkbookGet the currently focused Univer spreadsheet.
Returns
The currently focused Univer spreadsheet.
Example
const fWorkbook = univerAPI.getActiveWorkbook();
console.log(fWorkbook);getCollaboration()
getCollaboration(): FCollaborationGet the collaboration instance to manage the collaboration issue of the current univer.
Returns
The collaboration instance.
Example
const collaboration = univerAPI.getCollaboration();getCommandSheetTarget()
getCommandSheetTarget(commandInfo): Nullable<{
workbook: ...;
worksheet: ...;
}>Get the target of the sheet.
Parameters
| Parameter | Type | Description |
|---|---|---|
commandInfo | ICommandInfo<object> | The commandInfo of the command. |
Returns
Nullable<{
workbook: …;
worksheet: …;
}>
- The target of the sheet.
Example
univerAPI.addEvent(univerAPI.Event.CommandExecuted, (event) => {
const { options, ...commandInfo } = event;
const target = univerAPI.getCommandSheetTarget(commandInfo);
if (!target) return;
const { workbook, worksheet } = target;
console.log(workbook, worksheet);
});getComponentManager()
getComponentManager(): ComponentManagerGet the component manager
Returns
ComponentManager
The component manager
Example
const componentManager = univerAPI.getComponentManager();
console.log(componentManager);getCrosshairHighlightColor()
getCrosshairHighlightColor(): stringGet the color of the crosshair highlight.
Returns
string
The color of the crosshair highlight
Example
console.log(univerAPI.getCrosshairHighlightColor());getCrosshairHighlightEnabled()
getCrosshairHighlightEnabled(): booleanGet whether the crosshair highlight is enabled.
Returns
boolean
Whether the crosshair highlight is enabled
Example
console.log(univerAPI.getCrosshairHighlightEnabled());getCurrentLifecycleStage()
getCurrentLifecycleStage(): LifecycleStagesGet the current lifecycle stage.
Returns
LifecycleStages
- The current lifecycle stage.
Example
const stage = univerAPI.getCurrentLifecycleStage();
console.log(stage);getFormula()
getFormula(): FFormulaReturns
getHooks()
getHooks(): FHooksGet hooks.
Returns
FHooks instance
Deprecated
use addEvent instead.
getPermission()
getPermission(): FPermissionGet the PermissionInstance.
Returns
Deprecated
This function is deprecated and will be removed in version 0.6.0. Please use the function with the same name on the FWorkbook instance instead.
getProtectedRangeShadowStrategy()
getProtectedRangeShadowStrategy(): "always" | "non-editable" | "non-viewable" | "none"Get the current global strategy for showing the protected range shadow.
Returns
"always" | "non-editable" | "non-viewable" | "none"
The current shadow strategy
Example
const currentStrategy = univerAPI.getProtectedRangeShadowStrategy();
console.log(currentStrategy); // 'none', 'always', 'non-editable', or 'non-viewable'getProtectedRangeShadowStrategy$()
getProtectedRangeShadowStrategy$(): Observable<... | ... | ... | ...>Get an observable of the global strategy for showing the protected range shadow. This allows you to listen for strategy changes across all workbooks.
Returns
Observable<… | … | … | …>
An observable that emits the current shadow strategy
Example
const subscription = univerAPI.getProtectedRangeShadowStrategy$().subscribe((strategy) => {
console.log('Global strategy changed to:', strategy);
// Update UI or perform other actions
});
// Later, unsubscribe to clean up
subscription.unsubscribe();getSheetHooks()
getSheetHooks(): FSheetHooksReturns
Deprecated
use univerAPI.addEvent as instead.
getSheetTarget()
getSheetTarget(unitId, subUnitId): Nullable<{
workbook: ...;
worksheet: ...;
}>Get the target of the sheet.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | The unitId of the sheet. |
subUnitId | string | The subUnitId of the sheet. |
Returns
Nullable<{
workbook: …;
worksheet: …;
}>
- The target of the sheet.
Example
const unitId = 'workbook-01';
const subUnitId = 'sheet-0001';
const target = univerAPI.getSheetTarget(unitId, subUnitId);
if (!target) return;
const { workbook, worksheet } = target;
console.log(workbook, worksheet);getShortcut()
getShortcut(): FShortcutGet the Shortcut handler to interact with Univer’s shortcut functionalities.
Returns
the FShortcut object
Example
const fShortcut = univerAPI.getShortcut();
// Disable shortcuts of Univer
fShortcut.disableShortcut();
// Enable shortcuts of Univer
fShortcut.enableShortcut();
// Trigger a shortcut
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
const fRange = fWorksheet.getRange('A1');
fRange.activate();
fRange.setValue('Hello Univer');
console.log(fRange.getCellStyle().bold); // false
const pseudoEvent = new KeyboardEvent('keydown', {
key: 'b',
ctrlKey: true,
keyCode: univerAPI.Enum.KeyCode.B
});
const ifShortcutItem = fShortcut.triggerShortcut(pseudoEvent);
if (ifShortcutItem) {
const commandId = ifShortcutItem.id;
console.log(fRange.getCellStyle().bold); // true
}getUniverDoc()
getUniverDoc(id): FDocumentGet the document API handler by the document id.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | The document id. |
Returns
The document API instance.
getUniverSheet()
getUniverSheet(id): FWorkbookGet the spreadsheet API handler by the spreadsheet id.
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | The spreadsheet id. |
Returns
The spreadsheet API instance.
Example
const fWorkbook = univerAPI.getUniverSheet('Sheet1');
console.log(fWorkbook);
const fWorkbook = univerAPI.getWorkbook('Sheet1');
console.log(fWorkbook);getURL()
getURL(): URLReturn the URL of the current page.
Returns
URL
the URL object
Example
console.log(univerAPI.getURL());getUserManager()
getUserManager(): FUserManagerReturns
getWorkbook()
getWorkbook(id): FWorkbookParameters
| Parameter | Type |
|---|---|
id | string |
Returns
importDOCXToSnapshot()
importDOCXToSnapshot(file): Promise<IDocumentData>Import DOCX file to document data
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<IDocumentData>
Document data
Deprecated
Please use importDOCXToSnapshotAsync instead.
importDOCXToSnapshotAsync()
importDOCXToSnapshotAsync(file): Promise<IDocumentData>Import DOCX file to document data
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<IDocumentData>
A promise that resolves to the document data
Example
// Accepts a File object
const snapshot = await univerAPI.importDOCXToSnapshotAsync(file);
// Or accepts a URL to a remote file
// const snapshot = await univerAPI.importDOCXToSnapshotAsync('https://example.com/filename.docx');
console.log('Snapshot created:', snapshot);importDOCXToUnitId()
importDOCXToUnitId(file): Promise<string>Import DOCX file to unit id
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<string>
Unit id
Deprecated
Please use importDOCXToUnitIdAsync instead.
importDOCXToUnitIdAsync()
importDOCXToUnitIdAsync(file): Promise<string>Import DOCX file to unit id
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<string>
A promise that resolves to the unit id
Example
// Accepts a File object
const unitId = await univerAPI.importDOCXToUnitIdAsync(file);
// Or accepts a URL to a remote file
// const unitId = await univerAPI.importDOCXToUnitIdAsync('https://example.com/filename.docx');
const url = new URL(window.location.href);
const unit = url.searchParams.get('unit');
url.searchParams.set('unit', unitId);
url.searchParams.set('type', "1"); // The meaning of "1" is String(UniverInstanceType.UNIVER_DOC)
// Open the unit in the new window
window.open(url.toString(), '_blank');importXLSXToSnapshot()
importXLSXToSnapshot(file): Promise<IWorkbookData>Import XLSX file to workbook data
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<IWorkbookData>
Workbook data
Deprecated
Please use importXLSXToSnapshotAsync instead.
importXLSXToSnapshotAsync()
importXLSXToSnapshotAsync(file): Promise<IWorkbookData>Import XLSX file to workbook data
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<IWorkbookData>
A promise that resolves to the workbook data
Example
// Accepts a File object
const snapshot = await univerAPI.importXLSXToSnapshotAsync(file);
// Or accepts a URL to a remote file
// const snapshot = await univerAPI.importXLSXToSnapshotAsync('https://example.com/filename.xlsx');
console.log('Snapshot created:', snapshot); // see more: https://docs.univer.ai/en-US/guides/sheets/getting-started/workbook-data
// Create a new workbook with the snapshot
univerAPI.createWorkbook(snapshot);importXLSXToUnitId()
importXLSXToUnitId(file): Promise<string>Import XLSX file to unit id
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<string>
Unit id
Deprecated
Please use importXLSXToUnitIdAsync instead.
importXLSXToUnitIdAsync()
importXLSXToUnitIdAsync(file): Promise<string>Import XLSX file to unit id
Parameters
| Parameter | Type | Description |
|---|---|---|
file | string | File | File path or file object |
Returns
Promise<string>
A promise that resolves to the unit id
Example
// Accepts a File object
const unitId = await univerAPI.importXLSXToUnitIdAsync(file);
// Or accepts a URL to a remote file
// const unitId = await univerAPI.importXLSXToUnitIdAsync('https://example.com/filename.xlsx');
// Utilize automatic data loading in conjunction with collaborative editing. https://docs.univer.ai/en-US/guides/sheets/features/collaboration#loading-collaborative-documents
const url = new URL(window.location.href);
const unit = url.searchParams.get('unit');
url.searchParams.set('unit', unitId);
url.searchParams.set('type', "2"); // The meaning of "2" is String(UniverInstanceType.UNIVER_SHEET)
console.log('Unit URL:', url.toString());
// Open the unit in the new window
window.open(url.toString(), '_blank');isUIVisible()
isUIVisible(key): booleanGet the visibility of a built-in UI part.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | BuiltInUIPart | the built-in UI part |
Returns
boolean
the visibility
Example
// Hide header
univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false);
console.log(univerAPI.isUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER)); // falseloadLocales()
loadLocales(locale, locales): voidLoad locales for the given locale.
Parameters
| Parameter | Type | Description |
|---|---|---|
locale | string | A unique locale identifier. |
locales | ILanguagePack | The locales object containing the translations. |
Returns
void
Description
This method is utilized to load locales, which can be either built-in or custom-defined.
Example
univerAPI.loadLocales('esES', {
'Hello World': 'Hola Mundo',
});loadServerUnit()
loadServerUnit(
unitId,
unitType,
subUnitId?): Promise<any>Load the server unit by the given unit id and unit type.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | The unit id. |
unitType | UniverType | The unit type. |
subUnitId? | string | The sub unit id. |
Returns
Promise<any>
The promise with the unit model.
Example
const unitModel = await univerAPI.loadServerUnit('unitId', univerAPI.Enum.UniverInstanceType.UNIVER_SHEET);
console.log(unitModel, unitModel?.getSnapshot());loadServerUnitOfRevision()
loadServerUnitOfRevision(
unitId,
unitType,
rev): Promise<any>Load the server unit by the given unit id, unit type and revision.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | The unit id. |
unitType | UniverType | The unit type. |
rev | number | The revision number. |
Returns
Promise<any>
The promise with the unit model.
Example
const unitModel = await univerAPI.loadServerUnitOfRevision('unitId', univerAPI.Enum.UniverInstanceType.UNIVER_SHEET, 1);
console.log(unitModel, unitModel?.getSnapshot());newBlob()
newBlob(): FBlobCreate a new blob.
Returns
The new blob instance
Example
const blob = univerAPI.newBlob();newColor()
newColor(): ColorBuilderCreate a new color.
Returns
ColorBuilder
The new color instance
Example
const color = univerAPI.newColor();Deprecated
newDataValidation()
newDataValidation(): FDataValidationBuilderCreates a new instance of FDataValidationBuilder
Returns
A new instance of the FDataValidationBuilder class
Example
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
// Create a new data validation rule that requires a number between 1 and 10 fot the range A1:B10
const fRange = fWorksheet.getRange('A1:B10');
const rule = univerAPI.newDataValidation()
.requireNumberBetween(1, 10)
.setOptions({
allowBlank: true,
showErrorMessage: true,
error: 'Please enter a number between 1 and 10'
})
.build();
fRange.setDataValidation(rule);newDefinedName()
newDefinedName(): FDefinedNameBuilderCreate a new defined name builder.
Returns
- The defined name builder.
Example
const fWorkbook = univerAPI.getActiveWorkbook();
const definedNameBuilder = univerAPI.newDefinedName()
.setRef('Sheet1!$A$1')
.setName('MyDefinedName')
.setComment('This is a comment');
console.log(definedNameBuilder);
fWorkbook.insertDefinedNameBuilder(definedNameBuilder.build());newParagraphStyle()
newParagraphStyle(style?): ParagraphStyleBuilderCreate a new paragraph style.
Parameters
| Parameter | Type | Description |
|---|---|---|
style? | IParagraphStyle | The paragraph style |
Returns
ParagraphStyleBuilder
The new paragraph style instance
Example
const richText = univerAPI.newRichText({ body: { dataStream: 'Hello World\r\n' } });
const paragraphStyle = univerAPI.newParagraphStyle({ textStyle: { ff: 'Arial', fs: 12, it: univerAPI.Enum.BooleanNumber.TRUE, bl: univerAPI.Enum.BooleanNumber.TRUE } });
richText.insertParagraph(paragraphStyle);
const range = univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1');
range.setRichTextValueForCell(richText);newParagraphStyleValue()
newParagraphStyleValue(style?): ParagraphStyleValueCreate a new paragraph style value.
Parameters
| Parameter | Type | Description |
|---|---|---|
style? | IParagraphStyle | The paragraph style |
Returns
ParagraphStyleValue
The new paragraph style value instance
Example
const paragraphStyleValue = univerAPI.newParagraphStyleValue();newRichText()
newRichText(data?): RichTextBuilderCreate a new rich text.
Parameters
| Parameter | Type | Description |
|---|---|---|
data? | IDocumentData |
Returns
RichTextBuilder
The new rich text instance
Example
const richText = univerAPI.newRichText({ body: { dataStream: 'Hello World\r\n' } });
const range = univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1');
range.setRichTextValueForCell(richText);newRichTextValue()
newRichTextValue(data): RichTextValueCreate a new rich text value.
Parameters
| Parameter | Type | Description |
|---|---|---|
data | IDocumentData | The rich text data |
Returns
RichTextValue
The new rich text value instance
Example
const richTextValue = univerAPI.newRichTextValue({ body: { dataStream: 'Hello World\r\n' } });
const range = univerAPI.getActiveWorkbook().getActiveSheet().getRange('A1');
range.setRichTextValueForCell(richTextValue);newTextDecoration()
newTextDecoration(decoration?): TextDecorationBuilderCreate a new text decoration.
Parameters
| Parameter | Type | Description |
|---|---|---|
decoration? | ITextDecoration | The text decoration |
Returns
TextDecorationBuilder
The new text decoration instance
Example
const decoration = univerAPI.newTextDecoration();newTextStyle()
newTextStyle(style?): TextStyleBuilderCreate a new text style.
Parameters
| Parameter | Type | Description |
|---|---|---|
style? | ITextStyle | The text style |
Returns
TextStyleBuilder
The new text style instance
Example
const textStyle = univerAPI.newTextStyle();newTextStyleValue()
newTextStyleValue(style?): TextStyleValueCreate a new text style value.
Parameters
| Parameter | Type | Description |
|---|---|---|
style? | ITextStyle | The text style |
Returns
TextStyleValue
The new text style value instance
Example
const textStyleValue = univerAPI.newTextStyleValue();newTheadComment()
newTheadComment(): FTheadCommentBuilderCreate a new thread comment
Returns
The thead comment builder
Example
// Create a new comment
const richText = univerAPI.newRichText().insertText('hello univer');
const commentBuilder = univerAPI.newTheadComment()
.setContent(richText)
.setPersonId('mock-user-id')
.setDateTime(new Date('2025-02-21 14:22:22'))
.setId('mock-comment-id')
.setThreadId('mock-thread-id');
// Add the comment to the cell A1
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
const cell = fWorksheet.getRange('A1');
const result = await cell.addCommentAsync(commentBuilder);
console.log(result);onBeforeCommandExecute()
onBeforeCommandExecute(callback): IDisposableRegister a callback that will be triggered before invoking a command.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | CommandListener | The callback. |
Returns
IDisposable
The disposable instance.
Deprecated
use univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (event) => {}) instead.
onCommandExecuted()
onCommandExecuted(callback): IDisposableRegister a callback that will be triggered when a command is invoked.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | CommandListener | The callback. |
Returns
IDisposable
The disposable instance.
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommandExecuted, (event) => {}) instead.
onCommentAdded()
onCommentAdded(callback): IDisposableParameters
| Parameter | Type |
|---|---|
callback | (event) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentAdded, (params) => {}) as instead
onCommentDeleted()
onCommentDeleted(callback): IDisposableParameters
| Parameter | Type |
|---|---|
callback | (event) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentDeleted, (params) => {}) as instead
onCommentResolved()
onCommentResolved(callback): IDisposableParameters
| Parameter | Type |
|---|---|
callback | (event) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentResolved, (params) => {}) as instead
onCommentUpdated()
onCommentUpdated(callback): IDisposableParameters
| Parameter | Type |
|---|---|
callback | (event) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentUpdated, (params) => {}) as instead
onUniverSheetCreated()
onUniverSheetCreated(callback): IDisposableParameters
| Parameter | Type |
|---|---|
callback | (workbook) => void |
Returns
IDisposable
Deprecated
Use univerAPI.addEvent(univerAPI.Event.UnitCreated, () => {})
openDialog()
openDialog(dialog): IDisposableOpen a dialog.
Parameters
| Parameter | Type | Description |
|---|---|---|
dialog | IDialogPartMethodOptions | the dialog options |
Returns
IDisposable
the disposable object
Example
import { Button } from '@univerjs/design';
univerAPI.openDialog({
id: 'mock-dialog-id',
width: 500,
title: {
label: 'Dialog Title',
},
children: {
label: 'Dialog Content',
},
footer: {
title: (
<>
<Button onClick={() => { console.log('Cancel clicked') }}>Cancel</Button>
<Button variant="primary" onClick={() => { console.log('Confirm clicked') }} style={{marginLeft: '10px'}}>Confirm</Button>
</>
)
},
draggable: true,
mask: true,
maskClosable: true,
});openSidebar()
openSidebar(params): IDisposableOpen a sidebar.
Parameters
| Parameter | Type | Description |
|---|---|---|
params | ISidebarMethodOptions | the sidebar options |
Returns
IDisposable
the disposable object
Example
univerAPI.openSidebar({
id: 'mock-sidebar-id',
width: 300,
header: {
label: 'Sidebar Header',
},
children: {
label: 'Sidebar Content',
},
footer: {
label: 'Sidebar Footer',
},
onClose: () => {
console.log('Sidebar closed')
},
});openSiderbar()
openSiderbar(params): IDisposableOpen a sidebar.
Parameters
| Parameter | Type | Description |
|---|---|---|
params | ISidebarMethodOptions | the sidebar options |
Returns
IDisposable
the disposable object
Deprecated
Please use univerAPI.openSidebar instead.
paste()
paste(): Promise<boolean>Paste into the current selected position of the currently focused unit from your system clipboard.
Returns
Promise<boolean>
whether the paste operation is successful
Example
// Prevent failure due to loss of focus when executing copy and paste code in the console,
// this example listens for the cell click event and executes the copy and paste code.
univerAPI.addEvent(univerAPI.Event.CellClicked, async (params) => {
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
// Copy the range A1:B2 to the clipboard
const fRange = fWorksheet.getRange('A1:B2');
fRange.activate().setValues([
[1, 2],
[3, 4]
]);
await univerAPI.copy();
// Paste the copied content to the range C1:D2
const fRange2 = fWorksheet.getRange('C1');
fRange2.activate();
await univerAPI.paste();
// Check the pasted content
console.log(fWorksheet.getRange('C1:D2').getValues()); // [[1, 2], [3, 4]]
});pasteIntoSheet()
pasteIntoSheet(
htmlContent?,
textContent?,
files?): Promise<boolean>Paste clipboard data or custom data into the active sheet at the current selection position.
Parameters
| Parameter | Type | Description |
|---|---|---|
htmlContent? | string | The HTML content from the clipboard or custom data. |
textContent? | string | The plain text content from the clipboard or custom data. |
files? | File[] | The files from the clipboard or custom data. |
Returns
Promise<boolean>
A promise that resolves to true if the paste operation was successful, otherwise false.
Example
// Listen for the paste event and call the pasteIntoSheet method
document.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 data
univerAPI.pasteIntoSheet('<b>Bold Text</b>', 'Bold Text');redo()
redo(): Promise<boolean>Redo an editing on the currently focused document.
Returns
Promise<boolean>
redo result
Example
await univerAPI.redo();registerComponent()
registerComponent(
name,
component,
options?): IDisposableRegister an component.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the component. |
component | ComponentType | The component. |
options? | IComponentOptions | The options of the component. |
Returns
IDisposable
The disposable object.
Example
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet();
// Register a range loading component
const RangeLoading = () => {
const divStyle = {
width: '100%',
height: '100%',
backgroundColor: '#fff',
border: '1px solid #ccc',
boxSizing: 'border-box' as const,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center' as const,
transformOrigin: 'top left',
};
return (
<div style={divStyle}>
Loading...
</div>
);
};
univerAPI.registerComponent('RangeLoading', RangeLoading);
// Add the range loading component covering the range A1:C3
const range = fWorksheet.getRange('A1:C3');
const disposeable = fWorksheet.addFloatDomToRange(range, { componentKey: 'RangeLoading' }, {}, 'myRangeLoading');
setTimeout(() => {
disposeable?.dispose();
}, 2000);registerFunction()
registerFunction(config): IDisposableRegister a function to the spreadsheet.
Parameters
| Parameter | Type | Description |
|---|---|---|
config | IRegisterFunctionParams | The configuration of the function. |
Returns
IDisposable
The disposable instance.
Deprecated
Use univerAPI.getFormula().registerFunction instead.
registerSheetColumnHeaderExtension()
registerSheetColumnHeaderExtension(unitId, ...extensions): IDisposableRegister sheet column header render extensions.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | The unit id of the spreadsheet. |
…extensions | SheetExtension[] | The extensions to register. |
Returns
IDisposable
The disposable instance.
registerSheetMainExtension()
registerSheetMainExtension(unitId, ...extensions): IDisposableRegister sheet main render extensions.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | The unit id of the spreadsheet. |
…extensions | SheetExtension[] | The extensions to register. |
Returns
IDisposable
The disposable instance.
registerSheetRowHeaderExtension()
registerSheetRowHeaderExtension(unitId, ...extensions): IDisposableRegister sheet row header render extensions.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | The unit id of the spreadsheet. |
…extensions | SheetExtension[] | The extensions to register. |
Returns
IDisposable
The disposable instance.
registerUIPart()
registerUIPart(key, component): IDisposableRegister an component to a built-in UI part
Parameters
| Parameter | Type | Description |
|---|---|---|
key | BuiltInUIPart | the built-in UI part |
component | any | the react component |
Returns
IDisposable
Example
univerAPI.registerUIPart(univerAPI.Enum.BuiltInUIPart.CUSTOM_HEADER, () => React.createElement('h1', null, 'Custom Header'));runOnServer()
runOnServer(
scriptNameOrId,
func, ...
params): Promise<string>Execute a function in a Uniscript on the server.
Parameters
| Parameter | Type | Description |
|---|---|---|
scriptNameOrId | string | The name or the ID of the Uniscript to run. Name should end with “.us”. |
func | string | The function in the Uniscript to run |
…params | any[] | Parameters to the function |
Returns
Promise<string>
setCrosshairHighlightColor()
setCrosshairHighlightColor(color): FUniverSet the color of the crosshair highlight.
Parameters
| Parameter | Type | Description |
|---|---|---|
color | string | The color of the crosshair highlight, if the color not has alpha channel, the alpha channel will be set to 0.5 |
Returns
FUniver
The FUniver instance for chaining
Example
univerAPI.setCrosshairHighlightColor('#FF0000');
// or
univerAPI.setCrosshairHighlightColor('rgba(232, 11, 11, 0.2)');setCrosshairHighlightEnabled()
setCrosshairHighlightEnabled(enabled): FUniverEnable or disable crosshair highlight.
Parameters
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | Whether to enable the crosshair highlight |
Returns
FUniver
The FUniver instance for chaining
Example
univerAPI.setCrosshairHighlightEnabled(true);setCurrent()
setCurrent(unitId): voidSet a unit as the current unit and render a unit in the workbench’s main area. If you have multiple units in Univer, you should call this method to render the unit.
Parameters
| Parameter | Type | Description |
|---|---|---|
unitId | string | Unit to be rendered. |
Returns
void
Example
Let’s assume you have created two units, unit1 and unit2. Univer is rendering unit1 and you want to
render unit2.
univerAPI.setCurrent('unit2');This will render unit2 in the workbench’s main area.
setFreezeSync()
setFreezeSync(enabled): voidSet whether to enable synchronize the frozen state to other users in real-time collaboration.
Parameters
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | Whether to enable freeze sync. Default is true. |
Returns
void
Example
// Disable freeze sync
univerAPI.setFreezeSync(false);setLocale()
setLocale(locale): voidSet the current locale.
Parameters
| Parameter | Type | Description |
|---|---|---|
locale | string | A unique locale identifier. |
Returns
void
Example
univerAPI.setLocale('esES');setPermissionDialogVisible()
setPermissionDialogVisible(visible): voidSet visibility of unauthorized pop-up window
Parameters
| Parameter | Type | Description |
|---|---|---|
visible | boolean | visibility of unauthorized pop-up window |
Returns
void
Example
const univerAPI = FUniver.newAPI(univer);
univerAPI.setPermissionDialogVisible(false);setProtectedRangeShadowStrategy()
setProtectedRangeShadowStrategy(strategy): voidSet the global strategy for showing the protected range shadow. This will apply to all workbooks in the current Univer instance.
Parameters
| Parameter | Type | Description |
|---|---|---|
strategy | "always" | "non-editable" | "non-viewable" | "none" | 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 |
Returns
void
Example
// Always show shadows (default)
univerAPI.setProtectedRangeShadowStrategy('always');
// Only show shadows for non-editable ranges
univerAPI.setProtectedRangeShadowStrategy('non-editable');
// Only show shadows for non-viewable ranges
univerAPI.setProtectedRangeShadowStrategy('non-viewable');
// Never show shadows
univerAPI.setProtectedRangeShadowStrategy('none');setUIVisible()
setUIVisible(key, visible): FUniverSet the visibility of a built-in UI part.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | BuiltInUIPart | the built-in UI part |
visible | boolean | the visibility |
Returns
FUniver
the FUniver instance for chaining example
// Hide header, footer, and toolbar
univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, false)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, false);
// Show in 3 seconds
setTimeout(() => {
univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, true)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, true)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, true);
}, 3000);showMessage()
showMessage(options): FUniverShow a message.
Parameters
| Parameter | Type |
|---|---|
options | IMessageProps |
Returns
FUniver
the FUniver instance for chaining
Example
univerAPI.showMessage({
content: 'Success',
type: 'success',
duration: 3000,
});syncExecuteCommand()
syncExecuteCommand<P, R>(
id,
params?,
options?): RExecute a command with the given id and parameters synchronously.
Type Parameters
| Type Parameter | Default type |
|---|---|
P extends object | object |
R | boolean |
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | Identifier of the command. |
params? | P | Parameters of this execution. |
options? | IExecutionOptions | Options of this execution. |
Returns
R
The result of the execution. It is a boolean value by default which indicates the command is executed.
Example
univerAPI.syncExecuteCommand('sheet.command.set-range-values', {
value: { v: "Hello, Univer!" },
range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 }
});toggleDarkMode()
toggleDarkMode(isDarkMode): voidToggle dark mode on or off.
Parameters
| Parameter | Type | Description |
|---|---|---|
isDarkMode | boolean | Whether the dark mode is enabled. |
Returns
void
Example
univerAPI.toggleDarkMode(true);undo()
undo(): Promise<boolean>Undo an editing on the currently focused document.
Returns
Promise<boolean>
undo result
Example
await univerAPI.undo();newAPI()
static newAPI(wrapped): FUniverCreate an FUniver instance, if the injector is not provided, it will create a new Univer instance.
Parameters
| Parameter | Type | Description |
|---|---|---|
wrapped | any | The Univer instance or injector instance. |
Returns
FUniver
- The FUniver instance.
Static
Example
const univerAPI = FUniver.newAPI(univer);