类: FUniver
The root Facade API object to interact with Univer. Please use newAPI static method
to create a new instance.
继承
IFUniverNetworkMixin.IFUniverNetworkMixin.IFUniverEngineFormulaMixin.IFUniverSheetsMixin.IFUniverSheetsFormulaMixin.IFUnvierDataValidationMixin.IFUniverCommentMixin.IFUniverCollaborationClientMixin.IFUniverPivotTableEventMixin.IFUniverDocsUIMixin.IFUniverUIMixin.IFUniverSheetsUIMixin.IFUniverFindReplaceMixin.IFUniverCrosshairHighlightMixin.IFUniverWatermarkMixin.IFUniverSheetsZenEditorMixin.IFUniverNodeRuntimeMixin.IFUniverExchangeClientMixin
属性
| 属性 | 修饰符 | 类型 | 描述 |
|---|---|---|---|
|
|
|
Get the available built-in colors for the crosshair highlight. | |
|
|
( |
‐ |
访问器
Enum
Getter 签名
get Enum(): FEnum返回
Event
Getter 签名
get Event(): FEventName返回
Util
Getter 签名
get Util(): FUtil返回
FUtil
方法
addEvent()
addEvent<T>(event, callback): IDisposableAdd an event listener
类型参数
| 类型参数 |
|---|
T extends keyof IEventParamConfig |
参数
| 参数 | 类型 | 描述 |
|---|---|---|
event | T | key of event |
callback | (params) => void | callback when event triggered |
返回
IDisposable
The Disposable instance, for remove the listener
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
fonts | IFontConfig[] | The array of font configurations to add. |
返回
void
示例
univerAPI.addFonts([
{
value: 'CustomFont1',
label: 'Custom Font 1',
category: 'sans-serif',
},
{
value: 'CustomFont2',
label: 'Custom Font 2',
category: 'serif',
},
]);addWatermark()
调用签名
addWatermark(type, config): FUniverAdds a watermark to the unit. Supports both text and image watermarks based on the specified type.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
type | Text | The type of watermark to add is Text. |
config | ITextWatermarkConfig | The configuration object for the text type watermark. |
返回
FUniver
The FUniver instance for chaining.
抛出
Throws an error if the watermark type is unknown.
示例
univerAPI.addWatermark('text', {
content: 'Univer',
fontSize: 20,
repeat: true,
});调用签名
addWatermark(type, config): FUniverAdds a watermark to the unit. Supports both text and image watermarks based on the specified type.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
type | Image | The type of watermark to add is Image. |
config | IImageWatermarkConfig | The configuration object for the image type watermark. |
返回
FUniver
The FUniver instance for chaining.
抛出
Throws an error if the watermark type is unknown.
示例
univerAPI.addWatermark('image', {
url: 'https://avatars.githubusercontent.com/u/61444807?s=48&v=4',
width: 100,
height: 100,
});调用签名
addWatermark(type, config): FUniver参数
| 参数 | 类型 |
|---|---|
type | any |
config | any |
返回
FUniver
copy()
copy(): Promise<boolean>Copy the current selected content of the currently focused unit into your system clipboard.
返回
Promise<boolean>
whether the copy operation is successful
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
menuItem | IFacadeMenuItem | the menu item |
返回
the FMenu object
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
submenuItem | IFacadeSubmenuItem | the submenu item |
返回
the FSubmenu object
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
text | string | The text to find. |
返回
Promise<FTextFinder>
A promise that resolves to the text-finder instance.
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
data | Partial<IDocumentData> | The snapshot of the document. |
返回
FDocument API instance.
createUniverSheet()
createUniverSheet(data): FWorkbook参数
| 参数 | 类型 |
|---|---|
data | Partial<IWorkbookData> |
返回
已被弃用
use univerAPI.createWorkbook instead.
createWorkbook()
createWorkbook(data, options?): FWorkbookCreate a new spreadsheet and get the API handler of that spreadsheet.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
data | Partial<IWorkbookData> | The snapshot of the spreadsheet. |
options? | ICreateUnitOptions | The options of creating the spreadsheet. |
返回
FWorkbook API instance.
示例
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参数
| 参数 | 类型 |
|---|---|
cfg | IColumnsHeaderCfgParam |
返回
void
已被弃用
use same API in FWorkbook and FWorkSheet.
customizeRowHeader()
customizeRowHeader(cfg): void参数
| 参数 | 类型 |
|---|---|
cfg | IRowsHeaderCfgParam |
返回
void
已被弃用
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.
返回
FUniver
The FUniver instance for chaining.
示例
univerAPI.deleteWatermark();disposeUnit()
disposeUnit(unitId): booleanDispose the UniverSheet by the unitId. The UniverSheet would be unload from the application.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | The unit id of the UniverSheet. |
返回
boolean
Whether the Univer instance is disposed successfully.
示例
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.
类型参数
| 类型参数 | 默认类型 |
|---|---|
P extends object | object |
R | boolean |
参数
| 参数 | 类型 | 描述 |
|---|---|---|
id | string | Identifier of the command. |
params? | P | Parameters of this execution. |
options? | IExecutionOptions | Options of this execution. |
返回
Promise<R>
The result of the execution. It is a boolean value by default which indicates the command is executed.
示例
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
参数
| 参数 | 类型 | 描述 |
|---|---|---|
snapshot | IDocumentData | Document data |
返回
Promise<File>
DOCX file
示例
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
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | Unit id |
返回
Promise<File>
XLSX file
示例
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
参数
| 参数 | 类型 | 描述 |
|---|---|---|
snapshot | IWorkbookData | Workbook data |
返回
Promise<File>
XLSX file
已被弃用
Please use exportXLSXBySnapshotAsync instead.
exportXLSXBySnapshotAsync()
exportXLSXBySnapshotAsync(snapshot): Promise<File>Export XLSX file by workbook data
参数
| 参数 | 类型 | 描述 |
|---|---|---|
snapshot | IWorkbookData | Workbook data |
返回
Promise<File>
A promise that resolves to the XLSX file
示例
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
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | Unit id |
返回
Promise<File>
XLSX file
已被弃用
Please use exportXLSXByUnitIdAsync instead.
exportXLSXByUnitIdAsync()
exportXLSXByUnitIdAsync(unitId): Promise<File>Export XLSX file by unit id
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | Unit id |
返回
Promise<File>
A promise that resolves to the XLSX file
示例
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.
类型参数
| 类型参数 |
|---|
T extends keyof IEventParamConfig |
参数
| 参数 | 类型 | 描述 |
|---|---|---|
event | T | key of event |
params | IEventParamConfig[T] | params of event |
返回
boolean
should cancel
示例
this.fireEvent(univerAPI.Event.LifeCycleChanged, params);generatePivotTable()
generatePivotTable<T>(data, CustomDataFieldManager?): FGenericPivotTableCreate a pivot table instance that does not depend on a workbook
类型参数
| 类型参数 |
|---|
T extends DataFieldManager |
参数
| 参数 | 类型 | 描述 |
|---|---|---|
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 |
返回
The generated pivot table instance.
示例
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.
返回
The currently focused Univer document.
getActiveSheet()
getActiveSheet(): Nullable<{
workbook: ...;
worksheet: ...;
}>Get the active sheet.
返回
Nullable<{
workbook: …;
worksheet: …;
}>
The active sheet.
示例
const target = univerAPI.getActiveSheet();
if (!target) return;
const { workbook, worksheet } = target;
console.log(workbook, worksheet);getActiveUniverSheet()
getActiveUniverSheet(): FWorkbook返回
已被弃用
use univerAPI.getActiveWorkbook instead
getActiveWorkbook()
getActiveWorkbook(): FWorkbookGet the currently focused Univer spreadsheet.
返回
The currently focused Univer spreadsheet.
示例
const fWorkbook = univerAPI.getActiveWorkbook();
console.log(fWorkbook);getCollaboration()
getCollaboration(): FCollaborationGet the collaboration instance to manage the collaboration issue of the current univer.
返回
The collaboration instance.
示例
const collaboration = univerAPI.getCollaboration();getCommandSheetTarget()
getCommandSheetTarget(commandInfo): Nullable<{
workbook: ...;
worksheet: ...;
}>Get the target of the sheet.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
commandInfo | ICommandInfo<object> | The commandInfo of the command. |
返回
Nullable<{
workbook: …;
worksheet: …;
}>
- The target of the sheet.
示例
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
返回
ComponentManager
The component manager
示例
const componentManager = univerAPI.getComponentManager();
console.log(componentManager);getCrosshairHighlightColor()
getCrosshairHighlightColor(): stringGet the color of the crosshair highlight.
返回
string
The color of the crosshair highlight
示例
console.log(univerAPI.getCrosshairHighlightColor());getCrosshairHighlightEnabled()
getCrosshairHighlightEnabled(): booleanGet whether the crosshair highlight is enabled.
返回
boolean
Whether the crosshair highlight is enabled
示例
console.log(univerAPI.getCrosshairHighlightEnabled());getCurrentLifecycleStage()
getCurrentLifecycleStage(): LifecycleStagesGet the current lifecycle stage.
返回
LifecycleStages
- The current lifecycle stage.
示例
const stage = univerAPI.getCurrentLifecycleStage();
console.log(stage);getFormula()
getFormula(): FFormula返回
getHooks()
getHooks(): FHooksGet hooks.
返回
FHooks instance
已被弃用
use addEvent instead.
getPermission()
getPermission(): FPermissionGet the PermissionInstance.
返回
已被弃用
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.
返回
"always" | "non-editable" | "non-viewable" | "none"
The current shadow strategy
示例
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.
返回
Observable<… | … | … | …>
An observable that emits the current shadow strategy
示例
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(): FSheetHooks返回
已被弃用
use univerAPI.addEvent as instead.
getSheetTarget()
getSheetTarget(unitId, subUnitId): Nullable<{
workbook: ...;
worksheet: ...;
}>Get the target of the sheet.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | The unitId of the sheet. |
subUnitId | string | The subUnitId of the sheet. |
返回
Nullable<{
workbook: …;
worksheet: …;
}>
- The target of the sheet.
示例
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.
返回
the FShortcut object
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
id | string | The document id. |
返回
The document API instance.
getUniverSheet()
getUniverSheet(id): FWorkbookGet the spreadsheet API handler by the spreadsheet id.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
id | string | The spreadsheet id. |
返回
The spreadsheet API instance.
示例
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.
返回
URL
the URL object
示例
console.log(univerAPI.getURL());getUserManager()
getUserManager(): FUserManager返回
getWorkbook()
getWorkbook(id): FWorkbook参数
| 参数 | 类型 |
|---|---|
id | string |
返回
importDOCXToSnapshot()
importDOCXToSnapshot(file): Promise<IDocumentData>Import DOCX file to document data
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<IDocumentData>
Document data
已被弃用
Please use importDOCXToSnapshotAsync instead.
importDOCXToSnapshotAsync()
importDOCXToSnapshotAsync(file): Promise<IDocumentData>Import DOCX file to document data
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<IDocumentData>
A promise that resolves to the document data
示例
// 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
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<string>
Unit id
已被弃用
Please use importDOCXToUnitIdAsync instead.
importDOCXToUnitIdAsync()
importDOCXToUnitIdAsync(file): Promise<string>Import DOCX file to unit id
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<string>
A promise that resolves to the unit id
示例
// 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
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<IWorkbookData>
Workbook data
已被弃用
Please use importXLSXToSnapshotAsync instead.
importXLSXToSnapshotAsync()
importXLSXToSnapshotAsync(file): Promise<IWorkbookData>Import XLSX file to workbook data
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<IWorkbookData>
A promise that resolves to the workbook data
示例
// 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
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<string>
Unit id
已被弃用
Please use importXLSXToUnitIdAsync instead.
importXLSXToUnitIdAsync()
importXLSXToUnitIdAsync(file): Promise<string>Import XLSX file to unit id
参数
| 参数 | 类型 | 描述 |
|---|---|---|
file | string | File | File path or file object |
返回
Promise<string>
A promise that resolves to the unit id
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
key | BuiltInUIPart | the built-in UI part |
返回
boolean
the visibility
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
locale | string | A unique locale identifier. |
locales | ILanguagePack | The locales object containing the translations. |
返回
void
Description
This method is utilized to load locales, which can be either built-in or custom-defined.
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | The unit id. |
unitType | UniverType | The unit type. |
subUnitId? | string | The sub unit id. |
返回
Promise<any>
The promise with the unit model.
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | The unit id. |
unitType | UniverType | The unit type. |
rev | number | The revision number. |
返回
Promise<any>
The promise with the unit model.
示例
const unitModel = await univerAPI.loadServerUnitOfRevision('unitId', univerAPI.Enum.UniverInstanceType.UNIVER_SHEET, 1);
console.log(unitModel, unitModel?.getSnapshot());newBlob()
newBlob(): FBlobCreate a new blob.
返回
The new blob instance
示例
const blob = univerAPI.newBlob();newColor()
newColor(): ColorBuilderCreate a new color.
返回
ColorBuilder
The new color instance
示例
const color = univerAPI.newColor();已被弃用
newDataValidation()
newDataValidation(): FDataValidationBuilderCreates a new instance of FDataValidationBuilder
返回
A new instance of the FDataValidationBuilder class
示例
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.
返回
- The defined name builder.
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
style? | IParagraphStyle | The paragraph style |
返回
ParagraphStyleBuilder
The new paragraph style instance
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
style? | IParagraphStyle | The paragraph style |
返回
ParagraphStyleValue
The new paragraph style value instance
示例
const paragraphStyleValue = univerAPI.newParagraphStyleValue();newRichText()
newRichText(data?): RichTextBuilderCreate a new rich text.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
data? | IDocumentData |
返回
RichTextBuilder
The new rich text instance
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
data | IDocumentData | The rich text data |
返回
RichTextValue
The new rich text value instance
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
decoration? | ITextDecoration | The text decoration |
返回
TextDecorationBuilder
The new text decoration instance
示例
const decoration = univerAPI.newTextDecoration();newTextStyle()
newTextStyle(style?): TextStyleBuilderCreate a new text style.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
style? | ITextStyle | The text style |
返回
TextStyleBuilder
The new text style instance
示例
const textStyle = univerAPI.newTextStyle();newTextStyleValue()
newTextStyleValue(style?): TextStyleValueCreate a new text style value.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
style? | ITextStyle | The text style |
返回
TextStyleValue
The new text style value instance
示例
const textStyleValue = univerAPI.newTextStyleValue();newTheadComment()
newTheadComment(): FTheadCommentBuilderCreate a new thread comment
返回
The thead comment builder
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
callback | CommandListener | The callback. |
返回
IDisposable
The disposable instance.
已被弃用
use univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (event) => {}) instead.
onCommandExecuted()
onCommandExecuted(callback): IDisposableRegister a callback that will be triggered when a command is invoked.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
callback | CommandListener | The callback. |
返回
IDisposable
The disposable instance.
已被弃用
use univerAPI.addEvent(univerAPI.Event.CommandExecuted, (event) => {}) instead.
onCommentAdded()
onCommentAdded(callback): IDisposable参数
| 参数 | 类型 |
|---|---|
callback | (event) => void |
返回
IDisposable
已被弃用
use univerAPI.addEvent(univerAPI.Event.CommentAdded, (params) => {}) as instead
onCommentDeleted()
onCommentDeleted(callback): IDisposable参数
| 参数 | 类型 |
|---|---|
callback | (event) => void |
返回
IDisposable
已被弃用
use univerAPI.addEvent(univerAPI.Event.CommentDeleted, (params) => {}) as instead
onCommentResolved()
onCommentResolved(callback): IDisposable参数
| 参数 | 类型 |
|---|---|
callback | (event) => void |
返回
IDisposable
已被弃用
use univerAPI.addEvent(univerAPI.Event.CommentResolved, (params) => {}) as instead
onCommentUpdated()
onCommentUpdated(callback): IDisposable参数
| 参数 | 类型 |
|---|---|
callback | (event) => void |
返回
IDisposable
已被弃用
use univerAPI.addEvent(univerAPI.Event.CommentUpdated, (params) => {}) as instead
onUniverSheetCreated()
onUniverSheetCreated(callback): IDisposable参数
| 参数 | 类型 |
|---|---|
callback | (workbook) => void |
返回
IDisposable
已被弃用
Use univerAPI.addEvent(univerAPI.Event.UnitCreated, () => {})
openDialog()
openDialog(dialog): IDisposableOpen a dialog.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
dialog | IDialogPartMethodOptions | the dialog options |
返回
IDisposable
the disposable object
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
params | ISidebarMethodOptions | the sidebar options |
返回
IDisposable
the disposable object
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
params | ISidebarMethodOptions | the sidebar options |
返回
IDisposable
the disposable object
已被弃用
Please use univerAPI.openSidebar instead.
paste()
paste(): Promise<boolean>Paste into the current selected position of the currently focused unit from your system clipboard.
返回
Promise<boolean>
whether the paste operation is successful
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
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. |
返回
Promise<boolean>
A promise that resolves to true if the paste operation was successful, otherwise false.
示例
// 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.
返回
Promise<boolean>
redo result
示例
await univerAPI.redo();registerComponent()
registerComponent(
name,
component,
options?): IDisposableRegister an component.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
name | string | The name of the component. |
component | ComponentType | The component. |
options? | IComponentOptions | The options of the component. |
返回
IDisposable
The disposable object.
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
config | IRegisterFunctionParams | The configuration of the function. |
返回
IDisposable
The disposable instance.
已被弃用
Use univerAPI.getFormula().registerFunction instead.
registerSheetColumnHeaderExtension()
registerSheetColumnHeaderExtension(unitId, ...extensions): IDisposableRegister sheet column header render extensions.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | The unit id of the spreadsheet. |
…extensions | SheetExtension[] | The extensions to register. |
返回
IDisposable
The disposable instance.
registerSheetMainExtension()
registerSheetMainExtension(unitId, ...extensions): IDisposableRegister sheet main render extensions.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | The unit id of the spreadsheet. |
…extensions | SheetExtension[] | The extensions to register. |
返回
IDisposable
The disposable instance.
registerSheetRowHeaderExtension()
registerSheetRowHeaderExtension(unitId, ...extensions): IDisposableRegister sheet row header render extensions.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | The unit id of the spreadsheet. |
…extensions | SheetExtension[] | The extensions to register. |
返回
IDisposable
The disposable instance.
registerUIPart()
registerUIPart(key, component): IDisposableRegister an component to a built-in UI part
参数
| 参数 | 类型 | 描述 |
|---|---|---|
key | BuiltInUIPart | the built-in UI part |
component | any | the react component |
返回
IDisposable
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
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 |
返回
Promise<string>
setCrosshairHighlightColor()
setCrosshairHighlightColor(color): FUniverSet the color of the crosshair highlight.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
color | string | The color of the crosshair highlight, if the color not has alpha channel, the alpha channel will be set to 0.5 |
返回
FUniver
The FUniver instance for chaining
示例
univerAPI.setCrosshairHighlightColor('#FF0000');
// or
univerAPI.setCrosshairHighlightColor('rgba(232, 11, 11, 0.2)');setCrosshairHighlightEnabled()
setCrosshairHighlightEnabled(enabled): FUniverEnable or disable crosshair highlight.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
enabled | boolean | Whether to enable the crosshair highlight |
返回
FUniver
The FUniver instance for chaining
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
unitId | string | Unit to be rendered. |
返回
void
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
enabled | boolean | Whether to enable freeze sync. Default is true. |
返回
void
示例
// Disable freeze sync
univerAPI.setFreezeSync(false);setLocale()
setLocale(locale): voidSet the current locale.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
locale | string | A unique locale identifier. |
返回
void
示例
univerAPI.setLocale('esES');setPermissionDialogVisible()
setPermissionDialogVisible(visible): voidSet visibility of unauthorized pop-up window
参数
| 参数 | 类型 | 描述 |
|---|---|---|
visible | boolean | visibility of unauthorized pop-up window |
返回
void
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
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 |
返回
void
示例
// 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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
key | BuiltInUIPart | the built-in UI part |
visible | boolean | the visibility |
返回
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.
参数
| 参数 | 类型 |
|---|---|
options | IMessageProps |
返回
FUniver
the FUniver instance for chaining
示例
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.
类型参数
| 类型参数 | 默认类型 |
|---|---|
P extends object | object |
R | boolean |
参数
| 参数 | 类型 | 描述 |
|---|---|---|
id | string | Identifier of the command. |
params? | P | Parameters of this execution. |
options? | IExecutionOptions | Options of this execution. |
返回
R
The result of the execution. It is a boolean value by default which indicates the command is executed.
示例
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.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
isDarkMode | boolean | Whether the dark mode is enabled. |
返回
void
示例
univerAPI.toggleDarkMode(true);undo()
undo(): Promise<boolean>Undo an editing on the currently focused document.
返回
Promise<boolean>
undo result
示例
await univerAPI.undo();newAPI()
static newAPI(wrapped): FUniverCreate an FUniver instance, if the injector is not provided, it will create a new Univer instance.
参数
| 参数 | 类型 | 描述 |
|---|---|---|
wrapped | any | The Univer instance or injector instance. |
返回
FUniver
- The FUniver instance.
Static
示例
const univerAPI = FUniver.newAPI(univer);