Bases
| Packages | @univerjs-pro/bases, @univerjs-pro/bases-ui, @univerjs-pro/bases-dashboard, @univerjs-pro/bases-thread-comment, @univerjs-pro/bases-exchange-client |
|---|
Facade APIs for Base units, tables, fields, records, views, ranges, and workbench UI state.
Import
@univerjs-pro/bases/facadeand, for UI APIs,@univerjs-pro/bases-ui/facade.
Unit access
// univerAPIcreateBase(snapshot?: Partial<IBaseSnapshot>, options?: ICreateUnitOptions): FBasegetActiveBase(): FBase | nullgetBase(baseId: string): FBase | nullgetBases(): FBase[]Permissions
FBase.getPermission() returns unit-level Edit, Copy, Export, and Comment points. Tables, fields, records, views, Pivot Views, and Dashboards expose getPermission() for effective object-level editing.
import { UnitAction } from '@univerjs/protocol'const base = univerAPI.getActiveBase()if (!base) throw new Error('No active Base')await base.getPermission().setPoint(UnitAction.Copy, false)await base.getTables()[0]?.getPermission().setReadOnly()An object's canEdit() applies the Base and parent-object permissions as ceilings; enabling a child does not override a read-only parent.
Pivot Views and Dashboards
Import @univerjs-pro/bases-dashboard/facade to extend FBase:
import '@univerjs-pro/bases-dashboard/facade'const base = univerAPI.getActiveBase()const table = base?.getTables()[0]if (!base || !table) throw new Error('Base table not found')const pivot = base.createPivotView('Revenue by region', table.getId())const dashboard = base.createDashboard('Executive overview')dashboard.addPivotChart(table.getId(), pivot.getId(), { layout: { column: 0, row: 0, columnSpan: 6, rowSpan: 6 },})FBase provides getDashboards(), getDashboardById(), createDashboard(), getPivotViews(), getPivotView(), and createPivotView(). Pivot View Facades expose configuration and calculation; Dashboard Facades manage Pivot charts, table filters, text, images, Formula Shapes, and widget order.
Record attachments and comments
const record = univerAPI.getActiveBase()?.getTables()[0]?.getRecords()[0]const attachments = record?.getAttachments('files') ?? []record?.deleteAttachments('files', attachments)Import @univerjs-pro/bases-thread-comment/facade to add row-anchored comment helpers:
import '@univerjs-pro/bases-thread-comment/facade'await record?.createCommentAsync('Confirm this record.', { id: 'review-record-1' })const comments = await record?.listCommentsAsync()FBase
| Method | Description |
|---|---|
getBase | Get the underlying BaseDataModel. |
getId | Get the Base unit id. |
save | Serialize the complete current Base snapshot. |
getName, setName | Read or update the Base name. |
getTables | List existing tables in table order. |
getTableById, getTableByName | Resolve a table. |
insertTable | Insert a table with a generated default schema. |
deleteTable | Delete a table by facade or id. |
duplicateTable | Copy a table, optionally including records. |
getSchema | Get a compact schema without record values. |
getBase(): BaseDataModelgetId(): stringsave(): IBaseSnapshotgetName(): stringsetName(name: string): voidgetTables(): FBaseTable[]getTableById(tableId: string): FBaseTable | nullgetTableByName(displayName: string): FBaseTable | nullinsertTable(displayName: string, options?: { index?: number; table?: Partial<Omit<ITableSnapshot, 'id'>>; primaryFieldName?: string }): FBaseTabledeleteTable(table: FBaseTable | string): booleanduplicateTable(table: FBaseTable | string, options?: { includeRecords?: boolean; regenerateViewIds?: boolean }): FBaseTablegetSchema(): IBaseSchemaSnapshotTable names
A table display name must:
- contain 1–31 characters;
- not start or end with an apostrophe;
- not contain
: \ / ? * [ ]; - be unique within the Base, ignoring case.
insertTable() and FBaseTable.setName() throw when a name violates this contract. Renaming a table does not change the stable identifier returned by getFormulaName().
FBaseTable
| Category | Methods |
|---|---|
| Identity | getBase, getTable, getId, getName, setName, getFormulaName, getSchema |
| Hierarchy | getHierarchyFieldId, setHierarchyField |
| Search | search |
| Fields | getPrimaryFieldId, getPrimaryField, getFields, getFieldById, getFieldByName, addField |
| Records | getRecords, getRecordById, queryRecords, addRecord, addRecords, deleteRecords |
| Ranges | getRange, getDataRange |
| Views | getViews, getViewById, getViewByName, createView |
getBase(): BaseDataModelgetTable(): ITableSnapshotgetId(): stringgetHierarchyFieldId(): stringsetHierarchyField(fieldId: string | null): booleangetName(): stringsetName(displayName: string): booleangetFormulaName(): stringsearch(request: Omit<IBaseTableSearchRequest, 'table' | 'rows'>, viewId?: string): IBaseTableSearchResultgetPrimaryFieldId(): stringgetPrimaryField(): FBaseTableFieldgetFields(): FBaseTableField[]getFieldById(fieldId: string): FBaseTableField | nullgetFieldByName(fieldName: string): FBaseTableField | nulladdField(name: string, type: BaseFieldType, options?: IBaseAddFieldOptions | IBaseAddFormulaFieldOptions): FBaseTableFieldgetRecords(): FBaseTableRecord[]getRecordById(recordId: string): FBaseTableRecord | nullqueryRecords(options?: IListRecordOptions): IQueryRecordsResultaddRecord(values: Record<FieldId, BaseCellValue>, fieldKey?: BaseFieldKeyEnum, record?: Partial<Omit<IRecordSnapshot, 'id'>>): FBaseTableRecordaddRecords(records: Array<{ values: Record<FieldId, BaseCellValue>; fieldKey?: BaseFieldKeyEnum; record?: Partial<Omit<IRecordSnapshot, 'id'>> }>): FBaseTableRecord[]deleteRecords(recordIds: string[]): booleangetRange(row: number, column: number, numRows?: number, numColumns?: number): FBaseTableRangegetDataRange(): FBaseTableRangegetViews(): FBaseTableView[]getViewById(viewId: string): FBaseTableView | nullgetViewByName(viewName: string): FBaseTableView | nullcreateView(name: string, type: BaseViewType, options?: { index?: number; view?: Partial<Omit<IViewSnapshot, 'id'>> }): FBaseTableViewgetSchema(): IBaseTableSchemaSnapshotFormula fields use OOXML structured references and require IBaseAddFormulaFieldOptions.externalReferences. Use getFormulaName() instead of the display name because renaming a table does not change its stable formula name. Pass [] only when the formula has no external Unit qualifier.
const formulaTableName = table.getFormulaName()const total = table.addField('Total', univerAPI.Enum.BaseFieldType.Formula, { field: { config: { formula: `=SUM(${formulaTableName}[[#This Row],[Amount]],${formulaTableName}[[#This Row],[Tax]])`, }, }, externalReferences: [],})FBaseTableField
getId(): stringgetField(): IFieldSnapshotgetName(): stringgetType(): BaseFieldTypegetConfig(): FieldConfiggetDefaultValue(): IFieldSnapshot['defaultValue']getDescription(): string | undefinedisReadonly(): booleansetName(name: string): booleansetConfig(config: FieldConfig, options?: IBaseFormulaFieldWriteOptions): booleansetDefaultValue(defaultValue: IFieldSnapshot['defaultValue']): booleanupdate(patch: Partial<IFieldSnapshot>, options?: IBaseFormulaFieldWriteOptions): booleanchangeType(type: BaseFieldType, config?: FieldConfig, options?: IBaseFormulaFieldWriteOptions): booleandelete(): booleanmove(target: { beforeFieldId?: string; afterFieldId?: string }): booleanWriting Formula config through setConfig, update, or changeType also requires options.externalReferences. Metadata-only updates to an existing Formula field do not.
FBaseTableRecord
getId(): stringgetRecord(): IRecordSnapshotgetValue(fieldId: FieldId): BaseCellValuegetValues(): IRecordSnapshot['values']setValue(fieldId: FieldId, value: BaseCellValue): booleansetAttachments(fieldId: FieldId, attachments: IBaseAttachment[]): booleansetValues(values: Record<string, BaseCellValue>, fieldKey?: BaseFieldKeyEnum): booleandelete(): booleanduplicate(record?: Partial<Omit<IRecordSnapshot, 'id'>>): FBaseTableRecordsetOrderKey(orderKey: string): booleangetLinkedRecordIds(fieldId: FieldId): string[]setLinkedRecordIds(fieldId: FieldId, recordIds: readonly string[]): booleanaddLinkedRecord(fieldId: FieldId, recordId: string): booleanremoveLinkedRecord(fieldId: FieldId, recordId: string): booleangetParent(fieldId: FieldId): FBaseTableRecord | nullgetChildren(fieldId: FieldId): FBaseTableRecord[]getAncestors(fieldId: FieldId): FBaseTableRecord[]getDescendants(fieldId: FieldId): FBaseTableRecord[]setParent(fieldId: FieldId, parentRecordId: string | null, orderKey?: string): booleanaddChild(fieldId: FieldId, values: Record<FieldId, BaseCellValue>, fieldKey?: BaseFieldKeyEnum, record?: Partial<Omit<IRecordSnapshot, 'id'>>): FBaseTableRecordRecordLink helpers validate target records and preserve link order. Hierarchy methods use the table's single-value, same-table Parent RecordLink field. getHierarchyFieldId() may return a virtual id before the first hierarchy write; addChild() materializes it atomically. Base hierarchies support at most five levels.
Uploading or encoding a file is the caller's responsibility. setAttachments stores descriptors through the undoable Base command path.
record.setAttachments(attachmentsField.getId(), [ { id: uploadedFileId, name: 'report.pdf', mimeType: 'application/pdf', sourceType: univerAPI.Enum.ImageSourceType.UUID, source: uploadedFileId, },])FBaseTableView
getId(): stringgetView(): IViewSnapshotgetName(): stringgetType(): BaseViewTypesetName(name: string): booleangetConfig(): ViewSpecificConfigupdateConfig(patch: Partial<ViewSpecificConfig>): booleangetConditionalColorRules(): IBaseConditionalColorRule[]setConditionalColorRules(rules: IBaseConditionalColorRule[]): booleanaddConditionalColorRule(rule: IBaseConditionalColorRule): booleandeleteConditionalColorRule(ruleId: string): booleanclearConditionalColorRules(): booleangetFilter(): IFilterConfig | nullsetFilter(filter: IFilterConfig | null): booleangetSort(): ISortConfig[]setSort(sort: ISortConfig[]): booleangetGroup(): IGroupConfig[]setGroup(group: IGroupConfig[]): booleangetFieldSettings(fieldId: string): IViewFieldSettinggetVisibleFields(): FBaseTableField[]setFieldVisible(fieldId: string, visible: boolean): booleansetFieldWidth(fieldId: string, width: number): booleanmoveField(fieldId: string, target: { beforeFieldId?: string; afterFieldId?: string }): booleanmove(target: { beforeViewId?: string; afterViewId?: string }): booleandelete(): booleangetProjection(): BaseViewProjectionFBaseTableRange
getBaseId(): stringgetTableId(): stringgetRange(): IRangegetRow(): numbergetColumn(): numbergetNumRows(): numbergetNumColumns(): numbergetValues(): BaseCellValue[][]getValue(): BaseCellValuesetValue(value: BaseCellValue | IBaseCellData): booleansetValues(values: Array<Array<BaseCellValue | IBaseCellData>>): booleanclear(): booleanoffset(rowOffset: number, columnOffset: number, numRows?: number, numColumns?: number): FBaseTableRangeBases UI
Import @univerjs-pro/bases-ui/facade, then call univerAPI.getBaseUI().
| Category | Methods |
|---|---|
| Active state | getActiveTableId, getActiveViewId, activateTable, activateView |
| Selection and viewport | getSelection, setSelection, scrollToRecord, scrollToField |
| Editing | startEditingCell, stopEditingCell |
| Panels | openLeftSidebar, closeLeftSidebar, openRightSidebar, closeRightSidebar, openRecordDetail, openDraftRecordDetail, closeRecordDetail, openFieldConfigPanel, openViewSettingsPanel |
| People options | getPersonOptions, setPersonOptions, getGroupOptions, setGroupOptions |
getRenderedView() is part of the current public class but currently returns null.
Events and enums
@univerjs-pro/bases/facade adds table, field, record, view, cell-value, and BeforeBaseHierarchyChange / BaseHierarchyChanged events to univerAPI.Event. Conditional-color rule updates are reported through view changes.
The current enum Facade exposes BaseFieldType, BaseViewType, filtering and sorting enums, BaseFieldKeyEnum, BaseHierarchyErrorCode, BaseHierarchyInvalidReason, BaseConditionalColorTarget, BaseConditionalColorOperator, and BaseConditionalDateMode.
@univerjs-pro/bases, @univerjs-pro/bases-ui
File exchange
Register the Exchange Client and Bases Exchange Client plugins and import both Facade entries. These methods require a matching conversion backend; see Bases import/export.
importBaseToSnapshotAsync(file: File | string): Promise<IBaseSnapshot | undefined>importBaseToUnitIdAsync(file: File | string): Promise<string | undefined>exportBaseBySnapshotAsync(snapshot: IBaseSnapshot, format?: ExchangeFormat, tableId?: string): Promise<File | undefined>exportBaseByUnitIdAsync(unitId: string, format?: ExchangeFormat, tableId?: string): Promise<File | undefined>transformSnapshotJsonToBaseDataAsync(json: ISnapshotBlockJsonResponse): Promise<IBaseSnapshot>transformBaseDataToSnapshotJsonAsync(baseData: IBaseSnapshot): Promise<ISnapshotBlockJson>Imports accept XLSX, XLS, CSV, and TSV. Exports support XLSX (default), CSV, and TSV; specify tableId for single-table CSV/TSV exports. Load imported collaborative IDs with univerAPI.getCollaboration().loadBaseAsync(unitId).
How is this guide?