# Univer API Documentation ## Introduction Univer is a comprehensive TypeScript framework developed by DreamNum Co., Ltd. for building office productivity applications including spreadsheets, documents, and slides. The framework provides a Google Sheets-like API through its Facade pattern, enabling developers to programmatically interact with spreadsheet data, formatting, formulas, and more. Univer is designed as a monorepo architecture with modular packages, allowing developers to include only the features they need while maintaining a consistent API surface across all functionalities. The framework leverages dependency injection (via Injector) and a command-based architecture for state management, ensuring that all operations are undoable/redoable and can be synchronized across collaborative editing sessions. Univer supports both browser and Node.js environments, making it suitable for building web-based spreadsheet applications, server-side data processing pipelines, and headless automation scripts. The current version is 0.21.0, with all 61 packages in the monorepo sharing this unified version number. ## Core API Reference ### FUniver - Root API Object The `FUniver` class is the entry point for all Univer API interactions. Create an instance using the static `newAPI` method. ```typescript import { createUniver } from '@univerjs/presets'; import { UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core'; // Create Univer instance const { univer, univerAPI } = createUniver({ presets: [UniverSheetsCorePreset()] }); // Or create from existing Univer instance const univerAPI = FUniver.newAPI(univer); ``` #### Key Methods ```typescript // Get active workbook const fWorkbook = univerAPI.getActiveWorkbook(); // Undo/Redo operations await univerAPI.undo(); await univerAPI.redo(); // Execute commands univerAPI.executeCommand('sheet.command.set-range-values', { value: { v: "Hello, Univer!" }, range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }); // Toggle dark mode univerAPI.toggleDarkMode(true); // Set locale univerAPI.setLocale('zhCN'); // Event handling const disposable = univerAPI.addEvent(univerAPI.Event.CommandExecuted, (params) => { console.log('Command executed:', params.id); }); disposable.dispose(); // Remove listener // Dispose a unit univerAPI.disposeUnit(unitId); ``` ### FWorkbook - Workbook Operations The `FWorkbook` class provides methods for managing workbooks and their sheets. ```typescript const fWorkbook = univerAPI.getActiveWorkbook(); // Get workbook properties const id = fWorkbook.getId(); const name = fWorkbook.getName(); fWorkbook.setName('MyWorkbook'); // Save workbook data const snapshot = fWorkbook.save(); // Sheet operations const activeSheet = fWorkbook.getActiveSheet(); const allSheets = fWorkbook.getSheets(); const sheetByName = fWorkbook.getSheetByName('Sheet1'); const sheetById = fWorkbook.getSheetBySheetId('sheetId'); // Create new sheet const newSheet = fWorkbook.create('NewSheet', 100, 26); // name, rows, columns const insertedSheet = fWorkbook.insertSheet('AnotherSheet', { index: 0, sheet: { cellData: { 0: { 0: { v: 'Hello Univer!' } } } } }); // Set active sheet fWorkbook.setActiveSheet(sheetByName); // Delete sheet fWorkbook.deleteSheet(sheetByName); // or by id fWorkbook.deleteSheet('sheetId'); // Undo/Redo on workbook fWorkbook.undo(); fWorkbook.redo(); // Command listeners fWorkbook.onBeforeCommandExecute((command) => { console.log('Before command:', command); }); fWorkbook.onCommandExecuted((command) => { console.log('Command executed:', command); }); ``` ### FWorksheet - Worksheet Operations The `FWorksheet` class provides methods for working with individual sheets. ```typescript const fWorksheet = fWorkbook.getActiveSheet(); // Get worksheet properties const sheetId = fWorksheet.getSheetId(); const sheetName = fWorksheet.getSheetName(); const maxRows = fWorksheet.getMaxRows(); const maxColumns = fWorksheet.getMaxColumns(); // Get range by different methods const rangeByNotation = fWorksheet.getRange('A1:B2'); const rangeByCell = fWorksheet.getRange(0, 0); // row, column const rangeByArea = fWorksheet.getRange(0, 0, 3, 3); // row, column, numRows, numColumns // Row operations fWorksheet.insertRowBefore(2); // Insert row before row 3 fWorksheet.insertRowAfter(2); // Insert row after row 3 fWorksheet.insertRows(2, 5); // Insert 5 rows starting at row 3 // Column operations fWorksheet.insertColumnBefore(1); // Insert column before column B fWorksheet.insertColumnAfter(1); // Insert column after column B fWorksheet.insertColumns(1, 3); // Insert 3 columns starting at column B // Row/Column sizing fWorksheet.setRowHeight(0, 50); // Set row 1 height to 50px fWorksheet.setColumnWidth(0, 150); // Set column A width to 150px // Hide/Show rows and columns fWorksheet.hideRow(0); fWorksheet.showRow(0); fWorksheet.hideColumn(0); fWorksheet.showColumn(0); // Get selection const selection = fWorksheet.getSelection(); // Default styles const defaultStyle = fWorksheet.getDefaultStyle(); fWorksheet.setDefaultStyle({ fs: 12, ff: 'Arial' }); fWorksheet.setRowDefaultStyle(0, { bg: { rgb: '#f0f0f0' } }); fWorksheet.setColumnDefaultStyle(0, { ff: 'Helvetica' }); // Clear operations fWorksheet.clear(); // Clear all content and formatting fWorksheet.clear({ contentsOnly: true }); // Clear only content fWorksheet.clear({ formatOnly: true }); // Clear only formatting ``` ### FRange - Cell Range Operations The `FRange` class is the most feature-rich API for manipulating cell data, formatting, and formulas. #### Getting and Setting Values ```typescript const fRange = fWorksheet.getRange('A1:B2'); // Get values const value = fRange.getValue(); // First cell value const values = fRange.getValues(); // 2D array of values const rawValue = fRange.getRawValue(); // Raw value without formatting const displayValue = fRange.getDisplayValue(); // Displayed string value const displayValues = fRange.getDisplayValues(); // 2D array of displayed values // Set values fRange.setValue(123); fRange.setValue('Hello'); fRange.setValue({ v: 234, s: { bg: { rgb: '#ff0000' } } }); // Value with style // Set value for first cell only fRange.setValueForCell(456); // Set multiple values fRange.setValues([ [1, 2], [3, 4] ]); // Set with cell data format fRange.setValues([ [{ v: 0.2, s: { n: { pattern: '0%' } } }, { v: 45658, s: { n: { pattern: 'yyyy-mm-dd' } } }], [{ v: 1234.567, s: { n: { pattern: '#,##0.00' } } }, null] ]); ``` #### Formulas ```typescript // Get formulas const formula = fRange.getFormula(); // First cell formula const formulas = fRange.getFormulas(); // 2D array of formulas // Set formulas fRange.setFormula('=SUM(A2:A5)'); fRange.setFormulas([ ['=SUM(A2:A5)', '=SUM(B2:B5)'], ['=AVERAGE(A2:A5)', '=AVERAGE(B2:B5)'] ]); ``` #### Rich Text ```typescript // Create rich text const richText = univerAPI.newRichText() .insertText('Hello World') .setStyle(0, 5, { bl: 1, cl: { rgb: '#c81e1e' } }) // Bold red "Hello" .setStyle(6, 11, { it: 1, cl: { rgb: '#1e40af' } }); // Italic blue "World" // Set rich text fRange.setRichTextValueForCell(richText); // Get rich text const richTextValue = fRange.getValue(true); console.log(richTextValue.toPlainText()); // "Hello World" // Set multiple rich text values fRange.setRichTextValues([ [richText, richText], [null, null] ]); ``` #### Formatting - Fonts ```typescript // Font weight fRange.setFontWeight('bold'); fRange.setFontWeight('normal'); fRange.setFontWeight(null); // Reset // Font style fRange.setFontStyle('italic'); fRange.setFontStyle('normal'); // Font line (underline/strikethrough) fRange.setFontLine('underline'); fRange.setFontLine('line-through'); fRange.setFontLine('none'); // Font family fRange.setFontFamily('Arial'); fRange.setFontFamily('Helvetica'); // Font size fRange.setFontSize(14); fRange.setFontSize(24); // Font color fRange.setFontColor('#ff0000'); fRange.setFontColor('blue'); // Get font properties const fontFamily = fRange.getFontFamily(); const fontSize = fRange.getFontSize(); ``` #### Formatting - Background and Borders ```typescript // Background color fRange.setBackgroundColor('red'); fRange.setBackgroundColor('#00ff00'); fRange.setBackground('#0000ff'); // Get background const bgColor = fRange.getBackground(); const bgColors = fRange.getBackgrounds(); // 2D array // Borders fRange.setBorder( univerAPI.Enum.BorderType.ALL, // Border type univerAPI.Enum.BorderStyleTypes.THIN, // Border style '#ff0000' // Color (optional) ); ``` #### Formatting - Alignment ```typescript // Horizontal alignment fRange.setHorizontalAlignment('left'); fRange.setHorizontalAlignment('center'); fRange.setHorizontalAlignment('right'); // Vertical alignment fRange.setVerticalAlignment('top'); fRange.setVerticalAlignment('middle'); fRange.setVerticalAlignment('bottom'); // Get alignment const hAlign = fRange.getHorizontalAlignment(); const vAlign = fRange.getVerticalAlignment(); const hAligns = fRange.getHorizontalAlignments(); // 2D array const vAligns = fRange.getVerticalAlignments(); // 2D array ``` #### Formatting - Text Wrap and Rotation ```typescript // Text wrap fRange.setWrap(true); // Enable wrap fRange.setWrap(false); // Disable wrap // Wrap strategy fRange.setWrapStrategy(univerAPI.Enum.WrapStrategy.WRAP); fRange.setWrapStrategy(univerAPI.Enum.WrapStrategy.CLIP); fRange.setWrapStrategy(univerAPI.Enum.WrapStrategy.OVERFLOW); // Get wrap const isWrapped = fRange.getWrap(); const wraps = fRange.getWraps(); // 2D array const wrapStrategy = fRange.getWrapStrategy(); // Text rotation fRange.setTextRotation(45); // Rotate 45 degrees ``` #### Merging Cells ```typescript // Merge all cells in range fRange.merge(); // Merge horizontally (across rows) fRange.mergeAcross(); // Merge vertically (across columns) fRange.mergeVertically(); // Force merge (remove existing overlapping merges) fRange.merge({ isForceMerge: true }); // Check merge status const isMerged = fRange.isMerged(); const isPartOfMerge = fRange.isPartOfMerge(); // Unmerge fRange.breakApart(); ``` #### Cell Operations ```typescript // Insert cells fRange.insertCells(univerAPI.Enum.Dimension.ROWS); // Shift down fRange.insertCells(univerAPI.Enum.Dimension.COLUMNS); // Shift right // Delete cells fRange.deleteCells(univerAPI.Enum.Dimension.ROWS); // Shift up fRange.deleteCells(univerAPI.Enum.Dimension.COLUMNS); // Shift left // Clear content and/or formatting fRange.clear(); // Clear all fRange.clear({ contentsOnly: true }); // Clear content only fRange.clear({ formatOnly: true }); // Clear formatting only fRange.clearContent(); // Clear content fRange.clearFormat(); // Clear formatting ``` #### Range Navigation and Properties ```typescript // Get range properties const row = fRange.getRow(); // Starting row (0-based) const column = fRange.getColumn(); // Starting column (0-based) const lastRow = fRange.getLastRow(); // Ending row const lastColumn = fRange.getLastColumn(); // Ending column const width = fRange.getWidth(); // Number of columns const height = fRange.getHeight(); // Number of rows const range = fRange.getRange(); // IRange object // A1 notation const a1 = fRange.getA1Notation(); // "A1:B2" const a1WithSheet = fRange.getA1Notation(true); // "Sheet1!A1:B2" const a1Absolute = fRange.getA1Notation(false, univerAPI.Enum.AbsoluteRefType.ALL, univerAPI.Enum.AbsoluteRefType.ALL); // "$A$1:$B$2" // Offset to create new range const newRange = fRange.offset(1, 1); // Offset by 1 row and 1 column const newRange2 = fRange.offset(1, 1, 3); // With custom height const newRange3 = fRange.offset(1, 1, 3, 3); // With custom height and width // Get data region const dataRegion = fRange.getDataRegion(); // Expand to surrounding data const rowRegion = fRange.getDataRegion(univerAPI.Enum.Dimension.ROWS); const colRegion = fRange.getDataRegion(univerAPI.Enum.Dimension.COLUMNS); // Check if blank const isBlank = fRange.isBlank(); // Activate range/cell fRange.activate(); // Set as active range fRange.activateAsCurrentCell(); // Set as current cell (single cell only) // Iterate cells fRange.forEach((row, col, cell) => { console.log(`Cell at ${row},${col}:`, cell); }); ``` #### Auto Fill ```typescript // Auto-fill based on pattern const sourceRange = fWorksheet.getRange('A1:A4'); const targetRange = fWorksheet.getRange('A1:A20'); await sourceRange.autoFill(targetRange); // Default behavior await sourceRange.autoFill(targetRange, 'COPY'); // Copy values await sourceRange.autoFill(targetRange, 'SERIES'); // Fill series ``` #### Split Text to Columns ```typescript // Split text by auto-detected delimiter fRange.splitTextToColumns(); // Split with options fRange.splitTextToColumns(true); // Treat multiple delimiters as one // Split with specific delimiter fRange.splitTextToColumns(false, univerAPI.Enum.SplitDelimiterType.Comma); fRange.splitTextToColumns(false, univerAPI.Enum.SplitDelimiterType.Semicolon | univerAPI.Enum.SplitDelimiterType.Comma); // Split with custom delimiter fRange.splitTextToColumns(false, univerAPI.Enum.SplitDelimiterType.Custom, '#'); ``` #### Custom Metadata ```typescript // Set custom metadata fRange.setCustomMetaData({ key: 'value', count: 42 }); fRange.setCustomMetaDatas([ [{ key: 'a' }, { key: 'b' }], [{ key: 'c' }, { key: 'd' }] ]); // Get custom metadata const meta = fRange.getCustomMetaData(); const metas = fRange.getCustomMetaDatas(); // 2D array ``` #### Theme Styles ```typescript // Apply theme style fRange.useThemeStyle('default'); // Remove theme style fRange.removeThemeStyle('default'); fRange.useThemeStyle(undefined); // Also removes theme // Get applied theme const themeName = fRange.getUsedThemeStyle(); ``` #### Cell Styles ```typescript // Get cell style data const styleData = fRange.getCellStyleData(); const style = fRange.getCellStyle(); // TextStyleValue const styles = fRange.getCellStyles(); // 2D array // Get cell data const cellData = fRange.getCellData(); const cellDatas = fRange.getCellDatas(); // 2D array const cellDataGrid = fRange.getCellDataGrid(); // Same as getCellDatas ``` #### Permissions ```typescript // Get range permission instance const permission = fRange.getRangePermission(); // Protect the range await permission.protect({ name: 'Protected Area', allowEdit: false }); // Check protection status const isProtected = permission.isProtected(); const canEdit = permission.canEdit(); // Unprotect await permission.unprotect(); // Subscribe to changes permission.protectionChange$.subscribe(change => { console.log('Protection changed:', change); }); ``` ### Enums and Constants ```typescript // Access enums via univerAPI.Enum const { Dimension, BorderType, BorderStyleTypes, WrapStrategy, AbsoluteRefType, SplitDelimiterType } = univerAPI.Enum; // Dimension Dimension.ROWS; Dimension.COLUMNS; // Border types BorderType.ALL; BorderType.TOP; BorderType.BOTTOM; BorderType.LEFT; BorderType.RIGHT; BorderType.INNER; BorderType.OUTER; // Border styles BorderStyleTypes.NONE; BorderStyleTypes.THIN; BorderStyleTypes.MEDIUM; BorderStyleTypes.THICK; BorderStyleTypes.DASHED; BorderStyleTypes.DOTTED; // Wrap strategies WrapStrategy.UNSPECIFIED; WrapStrategy.WRAP; WrapStrategy.CLIP; WrapStrategy.OVERFLOW; // Absolute reference types AbsoluteRefType.NONE; AbsoluteRefType.ROW; AbsoluteRefType.COLUMN; AbsoluteRefType.ALL; ``` ### Events ```typescript // Available events via univerAPI.Event const { LifeCycleChanged, CommandExecuted, BeforeCommandExecute, Undo, Redo, BeforeUndo, BeforeRedo, DocCreated, DocDisposed } = univerAPI.Event; // Event listener examples univerAPI.addEvent(univerAPI.Event.CommandExecuted, (params) => { console.log('Command:', params.id, params.params); }); univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (params) => { // Cancel command by setting params.cancel = true if (params.id === 'some-command') { params.cancel = true; } }); univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, (params) => { console.log('Lifecycle stage:', params.stage); }); ``` ## Summary Univer provides a powerful and flexible foundation for building spreadsheet applications with its Google Sheets-compatible API. The framework excels at scenarios requiring programmatic spreadsheet manipulation, including automated report generation, data import/export pipelines, template-based document creation, and interactive web-based spreadsheet editors. Its command-based architecture ensures all operations are tracked for undo/redo functionality and can be synchronized in collaborative environments, making it ideal for building real-time collaborative editing applications similar to Google Sheets or Microsoft Excel Online. The modular architecture allows developers to start with core spreadsheet functionality and progressively add features like formulas, data validation, conditional formatting, charts, and collaborative editing as needed. Integration with existing systems is straightforward through the comprehensive Facade API, which abstracts away internal complexity while providing fine-grained control over cell data, formatting, and behavior. Whether building a simple data viewer, a complex financial modeling tool, or a full-featured office suite, Univer's extensible design and TypeScript-first approach make it an excellent choice for modern web and Node.js applications requiring spreadsheet capabilities.