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(): FEnum
Returns
Event
Get Signature
get Event(): FEventName
Returns
Util
Get Signature
get Util(): FUtil
Returns
FUtil
Methods
addEvent()
addEvent<T>(event, callback): IDisposable
Add an event listener
Type Parameters
Type Parameter |
---|
T extends keyof IEventParamConfig |
Parameters
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()`
addWatermark()
Call Signature
addWatermark(type, config): FUniver
Adds a watermark to the unit. Supports both text and image watermarks based on the specified type.
Parameters
Parameter | Type | Description |
---|---|---|
type | Text | The type of watermark to add is Text. |
config | ITextWatermarkConfig | The configuration object for the text type watermark. |
Returns
The FUniver instance for chaining.
Throws
Throws an error if the watermark type is unknown.
Example
univerAPI.addWatermark('text', {
content: 'Univer',
fontSize: 20,
repeat: true,
});
Call Signature
addWatermark(type, config): FUniver
Adds a watermark to the unit. Supports both text and image watermarks based on the specified type.
Parameters
Parameter | Type | Description |
---|---|---|
type | Image | The type of watermark to add is Image. |
config | IImageWatermarkConfig | The configuration object for the image type watermark. |
Returns
The FUniver instance for chaining.
Throws
Throws an error if the watermark type is unknown.
Example
univerAPI.addWatermark('image', {
url: 'https://avatars.githubusercontent.com/u/61444807?s=48&v=4',
width: 100,
height: 100,
});
Call Signature
addWatermark(type, config): FUniver
Parameters
Parameter | Type |
---|---|
type | any |
config | any |
Returns
copy()
copy(): Promise<boolean>
Copy the current selected content of the currently focused unit into your system clipboard.
Returns
Promise
<boolean
>
whether the copy operation is successful
Example
// Prevent failure due to loss of focus when executing copy and paste code in the console,
// this example listens for the cell click event and executes the copy and paste code.
univerAPI.addEvent(univerAPI.Event.CellClicked, async (params) => {
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
// Copy the range A1:B2 to the clipboard
const fRange = fWorksheet.getRange('A1:B2');
fRange.activate().setValues([
[1, 2],
[3, 4]
]);
await univerAPI.copy();
// Paste the copied content to the range C1:D2
const fRange2 = fWorksheet.getRange('C1');
fRange2.activate();
await univerAPI.paste();
// Check the pasted content
console.log(fWorksheet.getRange('C1:D2').getValues()); // [[1, 2], [3, 4]]
});
createMenu()
createMenu(menuItem): FMenu
Create a menu build object. You can insert new menus into the UI.
Parameters
Parameter | Type | Description |
---|---|---|
menuItem | IFacadeMenuItem | the menu item |
Returns
the FMenu object
Example
// Univer Icon can be viewed at https://univer.ai/en-US/icons
import { SmileSingle } from '@univerjs/icons'
// Create a custom menu with an univer icon
univerAPI.registerComponent('custom-menu-icon', SmileSingle);
univerAPI.createMenu({
id: 'custom-menu',
icon: 'custom-menu-icon',
title: 'Custom Menu',
tooltip: 'Custom Menu Tooltip',
action: () => {
console.log('Custom Menu Clicked');
},
}).appendTo('ribbon.start.others');
// Or
// Create a custom menu with an image icon
univerAPI.registerComponent('custom-menu-icon', () => {
return <img src="https://avatars.githubusercontent.com/u/61444807?s=48&v=4" alt="" style={{ width: '16px', height: '16px' }} />;
});
univerAPI.createMenu({
id: 'custom-menu',
icon: 'custom-menu-icon',
title: 'Custom Menu',
tooltip: 'Custom Menu Tooltip',
action: () => {
console.log('Custom Menu Clicked');
},
}).appendTo('ribbon.start.others');
// Or
// Create a custom menu without an icon
univerAPI.createMenu({
id: 'custom-menu',
title: 'Custom Menu',
tooltip: 'Custom Menu Tooltip',
action: () => {
console.log('Custom Menu Clicked');
},
}).appendTo('ribbon.start.others');
createSubmenu()
createSubmenu(submenuItem): FSubmenu
Create a menu that contains submenus, and later you can append this menu and its submenus to the UI.
Parameters
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();
const fRange = fWorksheet.getRange('A1:D10');
fRange.setValues([
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6],
[4, 5, 6, 7],
[5, 6, 7, 8],
[6, 7, 8, 9],
[7, 8, 9, 10],
[8, 9, 10, 11],
[9, 10, 11, 12],
[10, 11, 12, 13]
]);
// Create a text-finder to find the text '5'.
const textFinder = await univerAPI.createTextFinderAsync('5');
// Find all cells that contain the text '5'.
const matchCells = textFinder.findAll();
matchCells.forEach((cell) => {
console.log(cell.getA1Notation()); // D2, C3, B4, A5
});
createUniverDoc()
createUniverDoc(data): FDocument
Create a new document and get the API handler of that document.
Parameters
Parameter | Type | Description |
---|---|---|
data | Partial <IDocumentData > | The snapshot of the document. |
Returns
FDocument API instance.
createUniverSheet()
createUniverSheet(data): FWorkbook
Parameters
Parameter | Type |
---|---|
data | Partial <IWorkbookData > |
Returns
Deprecated
use univerAPI.createWorkbook
instead.
createWorkbook()
createWorkbook(data, options?): FWorkbook
Create 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): void
Parameters
Parameter | Type | Description |
---|---|---|
cfg | IColumnsHeaderCfgParam | The configuration of the column header. |
Returns
void
Deprecated
use same API in FWorkSheet. Customize the column header of the spreadsheet.
Example
univerAPI.customizeColumnHeader({ headerStyle: { fontColor: '#fff', size: 40, backgroundColor: '#4e69ee', fontSize: 9 }, columnsCfg: ['MokaII', undefined, null, { text: 'Size', textAlign: 'left' }] });
customizeRowHeader()
customizeRowHeader(cfg): void
Parameters
Parameter | Type | Description |
---|---|---|
cfg | IRowsHeaderCfgParam | The configuration of the row header. |
Returns
void
Deprecated
use same API in FWorkSheet. Customize the row header of the spreadsheet.
Example
univerAPI.customizeRowHeader({ headerStyle: { backgroundColor: 'pink', fontSize: 9 }, rowsCfg: ['MokaII', undefined, null, { text: 'Size', textAlign: 'left' }] });
deleteWatermark()
deleteWatermark(): FUniver
Deletes the currently applied watermark from the unit. This function retrieves the watermark service and invokes the method to remove any existing watermark configuration.
Returns
The FUniver instance for chaining.
Example
univerAPI.deleteWatermark();
disposeUnit()
disposeUnit(unitId): boolean
Dispose the UniverSheet by the unitId
. The UniverSheet would be unload from the application.
Parameters
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 }
});
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
const fWorkbook = univerAPI.getActiveWorkbook();
const snapshot = fWorkbook.save();
const file = await univerAPI.exportXLSXBySnapshotAsync(snapshot);
// Download the file
const url = URL.createObjectURL(file);
const a = document.createElement('a');
a.href = url;
a.download = 'filename.xlsx';
a.click();
URL.revokeObjectURL(url);
exportXLSXByUnitId()
exportXLSXByUnitId(unitId): Promise<File>
Export XLSX file by unit id
Parameters
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
const fWorkbook = univerAPI.getActiveWorkbook();
const unitId = fWorkbook.getId();
const file = await univerAPI.exportXLSXByUnitIdAsync(unitId);
// Download the file
const url = URL.createObjectURL(file);
const a = document.createElement('a');
a.href = url;
a.download = 'filename.xlsx';
a.click();
URL.revokeObjectURL(url);
generatePivotTable()
generatePivotTable<T>(data, CustomDataFieldManager?): FGenericPivotTable
Create a pivot table instance that does not depend on a workbook
Type Parameters
Type Parameter |
---|
T extends DataFieldManager |
Parameters
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(): FDocument
Get 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(): FWorkbook
Returns
Deprecated
use univerAPI.getActiveWorkbook
instead
getActiveWorkbook()
getActiveWorkbook(): FWorkbook
Get the currently focused Univer spreadsheet.
Returns
The currently focused Univer spreadsheet.
Example
const fWorkbook = univerAPI.getActiveWorkbook();
console.log(fWorkbook);
getCollaboration()
getCollaboration(): FCollaboration
Get the collaboration instance to manage the collaboration issue of the current univer.
Returns
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, (commandInfo) => {
const target = univerAPI.getCommandSheetTarget(commandInfo);
if (!target) return;
const { workbook, worksheet } = target;
console.log(workbook, worksheet);
});
getComponentManager()
getComponentManager(): ComponentManager
Get the component manager
Returns
ComponentManager
The component manager
Example
const componentManager = univerAPI.getComponentManager();
console.log(componentManager);
getCrosshairHighlightColor()
getCrosshairHighlightColor(): string
Get the color of the crosshair highlight.
Returns
string
The color of the crosshair highlight
Example
console.log(univerAPI.getCrosshairHighlightColor());
getCrosshairHighlightEnabled()
getCrosshairHighlightEnabled(): boolean
Get whether the crosshair highlight is enabled.
Returns
boolean
Whether the crosshair highlight is enabled
Example
console.log(univerAPI.getCrosshairHighlightEnabled());
getCurrentLifecycleStage()
getCurrentLifecycleStage(): LifecycleStages
Get the current lifecycle stage.
Returns
LifecycleStages
- The current lifecycle stage.
Example
const stage = univerAPI.getCurrentLifecycleStage();
console.log(stage);
getFormula()
getFormula(): FFormula
Returns
getHooks()
getHooks(): FHooks
Get hooks.
Returns
FHooks instance
Deprecated
use addEvent
instead.
getPermission()
getPermission(): FPermission
Get 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.
getSheetHooks()
getSheetHooks(): FSheetHooks
Returns
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(): FShortcut
Get 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): FDocument
Get 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): FWorkbook
Get 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(): URL
Return the URL of the current page.
Returns
URL
the URL object
Example
console.log(univerAPI.getURL());
getUserManager()
getUserManager(): FUserManager
Returns
getWorkbook()
getWorkbook(id): FWorkbook
Parameters
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): boolean
Get 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)); // false
newBlob()
newBlob(): FBlob
Create a new blob.
Returns
The new blob instance
Example
const blob = univerAPI.newBlob();
newColor()
newColor(): ColorBuilder
Create a new color.
Returns
ColorBuilder
The new color instance
Example
const color = univerAPI.newColor();
newDataValidation()
newDataValidation(): FDataValidationBuilder
Creates a new instance of FDataValidationBuilder
Returns
A new instance of the FDataValidationBuilder class
Example
const fWorkbook = univerAPI.getActiveWorkbook();
const fWorksheet = fWorkbook.getActiveSheet();
// Create a new data validation rule that requires a number between 1 and 10 fot the range A1:B10
const fRange = fWorksheet.getRange('A1:B10');
const rule = univerAPI.newDataValidation()
.requireNumberBetween(1, 10)
.setOptions({
allowBlank: true,
showErrorMessage: true,
error: 'Please enter a number between 1 and 10'
})
.build();
fRange.setDataValidation(rule);
newDefinedName()
newDefinedName(): FDefinedNameBuilder
Create a new defined name builder.
Returns
- The defined name builder.
Example
const fWorkbook = univerAPI.getActiveWorkbook();
const definedNameBuilder = univerAPI.newDefinedName()
.setRef('Sheet1!$A$1')
.setName('MyDefinedName')
.setComment('This is a comment');
console.log(definedNameBuilder);
fWorkbook.insertDefinedNameBuilder(definedNameBuilder.build());
newParagraphStyle()
newParagraphStyle(style?): ParagraphStyleBuilder
Create a new paragraph style.
Parameters
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?): ParagraphStyleValue
Create 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?): RichTextBuilder
Create 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): RichTextValue
Create 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?): TextDecorationBuilder
Create 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?): TextStyleBuilder
Create 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?): TextStyleValue
Create 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(): FTheadCommentBuilder
Create 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): IDisposable
Register 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): IDisposable
Register 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): IDisposable
Parameters
Parameter | Type |
---|---|
callback | (event ) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentAdded, (params) => {})
as instead
onCommentDeleted()
onCommentDeleted(callback): IDisposable
Parameters
Parameter | Type |
---|---|
callback | (event ) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentDeleted, (params) => {})
as instead
onCommentResolved()
onCommentResolved(callback): IDisposable
Parameters
Parameter | Type |
---|---|
callback | (event ) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentResolved, (params) => {})
as instead
onCommentUpdated()
onCommentUpdated(callback): IDisposable
Parameters
Parameter | Type |
---|---|
callback | (event ) => void |
Returns
IDisposable
Deprecated
use univerAPI.addEvent(univerAPI.Event.CommentUpdated, (params) => {})
as instead
onUniverSheetCreated()
onUniverSheetCreated(callback): IDisposable
Parameters
Parameter | Type |
---|---|
callback | (workbook ) => void |
Returns
IDisposable
Deprecated
Use univerAPI.addEvent(univerAPI.Event.UnitCreated, () => {})
openDialog()
openDialog(dialog): IDisposable
Open 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 type="primary" onClick={() => { console.log('Confirm clicked') }} style={{marginLeft: '10px'}}>Confirm</Button>
</>
)
},
draggable: true,
mask: true,
maskClosable: true,
});
openSidebar()
openSidebar(params): IDisposable
Open a sidebar.
Parameters
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): IDisposable
Open 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]]
});
redo()
redo(): Promise<boolean>
Redo an editing on the currently focused document.
Returns
Promise
<boolean
>
redo result
Example
univerAPI.redo();
registerComponent()
registerComponent(
name,
component,
options?): IDisposable
Register an component.
Parameters
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): IDisposable
Register 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): IDisposable
Register 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): IDisposable
Register 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): IDisposable
Register 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): IDisposable
Register 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): FUniver
Set 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
The FUniver instance for chaining
Example
univerAPI.setCrosshairHighlightColor('#FF0000');
// or
univerAPI.setCrosshairHighlightColor('rgba(232, 11, 11, 0.2)');
setCrosshairHighlightEnabled()
setCrosshairHighlightEnabled(enabled): FUniver
Enable or disable crosshair highlight.
Parameters
Parameter | Type | Description |
---|---|---|
enabled | boolean | Whether to enable the crosshair highlight |
Returns
The FUniver instance for chaining
Example
univerAPI.setCrosshairHighlightEnabled(true);
setCurrent()
setCurrent(unitId): void
Set a unit as the current unit and render a unit in the workbench’s main area. If you have multiple units in Univer, you should call this method to render the unit.
Parameters
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.
setUIVisible()
setUIVisible(key, visible): FUniver
Set the visibility of a built-in UI part.
Parameters
Parameter | Type | Description |
---|---|---|
key | BuiltInUIPart | the built-in UI part |
visible | boolean | the visibility |
Returns
the FUniver instance for chaining example
// Hide header, footer, and toolbar
univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, false)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, false)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, false);
// Show in 3 seconds
setTimeout(() => {
univerAPI.setUIVisible(univerAPI.Enum.BuiltInUIPart.HEADER, true)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.FOOTER, true)
.setUIVisible(univerAPI.Enum.BuiltInUIPart.TOOLBAR, true);
}, 3000);
showMessage()
showMessage(options): FUniver
Show a message.
Parameters
Parameter | Type |
---|---|
options | IMessageProps |
Returns
the FUniver instance for chaining
Example
univerAPI.showMessage({
content: 'Success',
type: 'success',
duration: 3000,
});
syncExecuteCommand()
syncExecuteCommand<P, R>(
id,
params?,
options?): R
Execute a command with the given id and parameters synchronously.
Type Parameters
Type 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 }
});
undo()
undo(): Promise<boolean>
Undo an editing on the currently focused document.
Returns
Promise
<boolean
>
undo result
Example
univerAPI.undo();
newAPI()
static newAPI(wrapped): FUniver
Create an FUniver instance, if the injector is not provided, it will create a new Univer instance.
Parameters
Parameter | Type | Description |
---|---|---|
wrapped | any | The Univer instance or injector instance. |
Returns
- The FUniver instance.
Static
Example
const univerAPI = FUniver.newAPI(univer);