Range & Selection & Cell
This page describes ranges, selections, and cells. It explains how to read and write values through a range, how to control the selection, and how to handle pointer, editing, and clipboard events.
Range
A range is a rectangular area of a worksheet. It can be defined by the starting row and column together with the number of rows and columns, or by the starting row and column together with the ending row and column.
Most spreadsheet operations are performed through the Range API: setting and reading values, setting and reading styles, and so on.
For the complete type definitions of the range APIs, see FRange FacadeAPI.
Create a range
A range requires a starting row, a starting column, and a size.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Create a range of A1 cell:const fRange = fWorksheet.getRange(0, 0)console.log(fRange, fRange.getA1Notation())// Creates a range of A1:B2:const fRange2 = fWorksheet.getRange(0, 0, 2, 2)console.log(fRange2, fRange2.getA1Notation())A range can also be described in A1 notation, with an optional worksheet name in front:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Get the A1:B2 range on named Sheet1const fRange1 = fWorksheet.getRange('Sheet1!A1:B2')console.log(fRange1, fRange1.getA1Notation())// Get a single cell A1const fRange2 = fWorksheet.getRange('A1')console.log(fRange2, fRange2.getA1Notation())// Get the A1:B2 rangeconst fRange3 = fWorksheet.getRange('A1:B2')console.log(fRange3, fRange3.getA1Notation())// Get the range of column Aconst fRange4 = fWorksheet.getRange('A:A')console.log(fRange4, fRange4.getA1Notation())// Get the range of row 1const fRange5 = fWorksheet.getRange('1:1')console.log(fRange5, fRange5.getA1Notation())Get range data
Read the top-left cell of a range:
const fWorkbook = univerAPI.getActiveWorkbook()if (!fWorkbook) throw new Error('No active workbook')const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')console.log(fRange.getValue()) // The value of the top-left cell in the rangeconsole.log(fRange.getRawValue()) // The raw value of the top-left cell in the rangeconsole.log(fRange.getDisplayValue()) // The displayed value of the top-left cell in the rangeconsole.log(fRange.getCellData()) // The cell data of the top-left cell in the rangeconst value = fRange.getValue(true)console.log(value)if (value !== null && typeof value === 'object') { console.log(value.toPlainText())}getValue(true) returns a rich-text object. Empty cells return null or undefined; ordinary cells return a string, number, or boolean. Call toPlainText() only on a rich-text object.
Read every value in the range:
const fWorkbook = univerAPI.getActiveWorkbook()if (!fWorkbook) throw new Error('No active workbook')const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')console.log(fRange.getValues()) // The values of all cells in the rangeconsole.log(fRange.getRawValues()) // The raw values of all cells in the rangeconsole.log(fRange.getDisplayValues()) // The displayed values of all cells in the rangeconsole.log(fRange.getCellDataGrid()) // The cell data of all cells in the rangeconsole.log(fRange.getValues(true))Read every formula in the range:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')console.log(fRange.getFormula()) // The formula of the top-left cell in the rangeconsole.log(fRange.getFormulas()) // The formulas of all cells in the rangeSet range value
Set a single value
Passing a value or a cell object overwrites every cell in the range. A string that starts with = is interpreted as a formula.
For example, the following code sets all of A1:B2 to Hello, Univer:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange.setValue('Hello, Univer')The following code sets C1 to =A1+B1, so the result appears outside the input cells:
const fWorkbook = univerAPI.getActiveWorkbook()if (!fWorkbook) throw new Error('No active workbook')const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('C1')fRange.setValue('=A1+B1')A cell object can be passed instead:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange.setValue({ v: 'Hello, Univer', custom: { key: 'value', },})An ICellData object that supplies v or p without f and si replaces the existing formula and its shared-formula identity. Supplying f without si also detaches the cell from its previous shared formula. A patch that carries only style or custom fields preserves the formula. Writing v does not clear rich text, so include p: null when a value replaces rich text. The same rules apply to cell objects passed to setValues().
To set only the top-left cell of the range, use FRange.setValueForCell:
fRange.setValueForCell('Hello, Univer')Set multiple values with an array
The array must match the height and width of the range.
The entries can be plain values or cell objects.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange.setValues([ ['A1', 'B1'], ['A2', 'B2'],])fRange.setValues([ [{ v: 'A1' }, { v: 'B1' }], [{ v: 'A2' }, { v: 'B2' }],])Set multiple values with an object
When an object is passed, the top-level key is the row number and the nested key is the column number. The range does not need to match the size of the object.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange.setValues({ 0: { 0: 'A1', 1: 'B1', }, 1: { 0: 'A2', 1: 'B2', },})Clear range data
FRange.clearclears the content and formatting of the range.FRange.clearContentclears only the content.FRange.clearFormatclears only the formatting.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorkSheet = fWorkbook.getActiveSheet()const fRange = fWorkSheet.getRange('A1:D10')// Clears content and formatting information of the range.fRange.clear()Get range style
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')console.log(fRange.getCellStyleData()) // The style data of the top-left cell in the rangeconsole.log(fRange.getCellStyle()) // The style of the top-left cell in the rangeconsole.log(fRange.getCellStyles()) // The styles of all cells in the rangeSet range style
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange .setValues([ [1, 2], [3, 4], ]) .setFontWeight('bold') .setFontLine('underline') .setFontFamily('Arial') .setFontSize(24) .setFontColor('red')Clear range style
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange.setFontWeight(null).setFontLine(null).setFontFamily(null).setFontSize(null).setFontColor(null)Format painter on rows and columns
Select the cells that carry the formatting to be copied, activate the format painter, and then click or drag the target row headers or column headers to apply the formatting to entire rows or columns. Target cells in the grid can also be selected.
Selection
Arrow-key navigation, selection animation, the fill handle, and drag overwrite prompts are described in selection and dragging settings.
Univer Sheets supports multiple selection areas, so a selection is an array of ranges, and these ranges are manipulated through the Range API.
APIs are also available to get the current selection, set the selection, and listen for changes to the selection.
For the complete type definitions of the selection APIs, see FSelection FacadeAPI.
Get active selection
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Activate the new selection of A1:B2const fRange = fWorksheet.getRange('A1:B2')fRange.activate()// Get the current active selectionconst fSelection = fWorksheet.getSelection()console.log(fSelection)const activeRange = fSelection.getActiveRange()console.log(activeRange.getA1Notation()) // A1:B2Set selection
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Set the selection to A1:B2 by FRangeconst fRange = fWorksheet.getRange('A1:B2')fRange.activate()// Set the selection to C1:D2 by FWorksheetfWorksheet.setActiveSelection(fWorksheet.getRange('C1:D2'))Get current cell
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Activate the new selection of A10:B11const fRange = fWorksheet.getRange('A10:B11')fRange.activate()// Get the current active celllet fSelection = fWorksheet.getSelection()const { actualRow, actualColumn } = fSelection.getCurrentCell()console.log(fWorksheet.getRange(actualRow, actualColumn).getA1Notation()) // A10// Update the new active cell to B11fSelection = fSelection.updatePrimaryCell(fWorksheet.getRange('B11'))const { actualRow: newRow, actualColumn: newColumn } = fSelection.getCurrentCell()console.log(fWorksheet.getRange(newRow, newColumn).getA1Notation()) // B11Disable/enable/hide/show selection
A disabled selection stops responding to input. transparentSelection hides the selection instead. Unlike disableSelection, transparentSelection keeps the selection functional; it is only invisible.
const fWorkbook = univerAPI.getActiveWorkbook()// Disable selectionfWorkbook.disableSelection()// Enable selectionfWorkbook.enableSelection()// Hide selectionfWorkbook.transparentSelection()// Show selectionfWorkbook.showSelection()Listen for selection changes
univerAPI.addEvent(univerAPI.Event.SelectionChanged, (params) => { const { worksheet, workbook, selections } = params console.log(params)})Cell
Cell data is stored in the worksheet as a two-dimensional Map, where the first index is the row number and the second is the column number.
A typical cell object is shown below:
const data = { v: 'Hello, Univer', s: 'styleId', t: CellValueType.STRING,}For the complete field descriptions, see Configure Cell Data.
Good to know
- A cell operation is a range operation on a range one row high and one column wide. The capabilities of a range are described in Range.
- The Univer API plugin also stores extended cell attributes in the
resourcesproperty of theWorkbook. See Plugin Custom Model.
Advanced range operations
Insert cells
FRange.insertCells inserts empty cells into the range. Existing data in the sheet is shifted away from the inserted range along the specified dimension.
// Assume the active sheet empty sheet.const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const values = [ [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8],]// Set the range A1:D5 with some values, the range A1:D5 will be:// 1 | 2 | 3 | 4// 2 | 3 | 4 | 5// 3 | 4 | 5 | 6// 4 | 5 | 6 | 7// 5 | 6 | 7 | 8const fRange = fWorksheet.getRange('A1:D5')fRange.setValues(values)console.log(fWorksheet.getRange('A1:D5').getValues()) // [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]// Insert the empty cells into the range A1:B2 along the columns dimension, the range A1:D5 will be:// | | 1 | 2// | | 2 | 3// 3 | 4 | 5 | 6// 4 | 5 | 6 | 7// 5 | 6 | 7 | 8const fRange2 = fWorksheet.getRange('A1:B2')fRange2.insertCells(univerAPI.Enum.Dimension.COLUMNS)console.log(fWorksheet.getRange('A1:D5').getValues()) // [[null, null, 1, 2], [null, null, 2, 3], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]// Set the range A1:D5 values again, the range A1:D5 will be:// 1 | 2 | 3 | 4// 2 | 3 | 4 | 5// 3 | 4 | 5 | 6// 4 | 5 | 6 | 7// 5 | 6 | 7 | 8fRange.setValues(values)// Insert the empty cells into the range A1:B2 along the rows dimension, the range A1:D5 will be:// | | 3 | 4// | | 4 | 5// 1 | 2 | 5 | 6// 2 | 3 | 6 | 7// 3 | 4 | 7 | 8const fRange3 = fWorksheet.getRange('A1:B2')fRange3.insertCells(univerAPI.Enum.Dimension.ROWS)console.log(fWorksheet.getRange('A1:D5').getValues()) // [[null, null, 3, 4], [null, null, 4, 5], [1, 2, 5, 6], [2, 3, 6, 7], [3, 4, 7, 8]]Delete cells
FRange.deleteCells deletes the cells in the range. Existing data in the sheet is shifted toward the deleted range along the specified dimension.
// Assume the active sheet empty sheet.const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const values = [ [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8],]// Set the range A1:D5 with some values, the range A1:D5 will be:// 1 | 2 | 3 | 4// 2 | 3 | 4 | 5// 3 | 4 | 5 | 6// 4 | 5 | 6 | 7// 5 | 6 | 7 | 8const fRange = fWorksheet.getRange('A1:D5')fRange.setValues(values)console.log(fWorksheet.getRange('A1:D5').getValues()) // [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]// Delete the range A1:B2 along the columns dimension, the range A1:D5 will be:// 3 | 4 | |// 4 | 5 | |// 3 | 4 | 5 | 6// 4 | 5 | 6 | 7// 5 | 6 | 7 | 8const fRange2 = fWorksheet.getRange('A1:B2')fRange2.deleteCells(univerAPI.Enum.Dimension.COLUMNS)console.log(fWorksheet.getRange('A1:D5').getValues()) // [[3, 4, null, null], [4, 5, null, null], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]// Set the range A1:D5 values again, the range A1:D5 will be:// 1 | 2 | 3 | 4// 2 | 3 | 4 | 5// 3 | 4 | 5 | 6// 4 | 5 | 6 | 7// 5 | 6 | 7 | 8fRange.setValues(values)// Delete the range A1:B2 along the rows dimension, the range A1:D5 will be:// 3 | 4 | 3 | 4// 4 | 5 | 4 | 5// 5 | 6 | 5 | 6// | | 6 | 7// | | 7 | 8const fRange3 = fWorksheet.getRange('A1:B2')fRange3.deleteCells(univerAPI.Enum.Dimension.ROWS)console.log(fWorksheet.getRange('A1:D5').getValues()) // [[3, 4, 3, 4], [4, 5, 4, 5], [5, 6, 5, 6], [null, null, 6, 7], [null, null, 7, 8]]Merge cells
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Merge B1:B2const fRange = fWorksheet.getRange('B1:B2')fRange.merge()console.log(fRange.isMerged()) // true// A1:B2 is mergedconst fRange2 = fWorksheet.getRange('A1:B2')console.log(fRange2.isMerged()) // falseconsole.log(fRange2.isPartOfMerge()) // true// Break apart the merged rangefRange2.breakApart()// merge horizontally: fRange2.mergeAcross();// merge vertically: fRange2.mergeVertically();// Get all merged ranges in the worksheet: fWorksheet.getMergedRanges();Highlight range
FRange.highlight highlights the range with the specified style and primary cell.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Highlight the range C3:E5 with default styleconst fRange = fWorksheet.getRange('C3:E5')fRange.highlight()// Highlight the range C7:E9 with custom style and primary cell D8const fRange2 = fWorksheet.getRange('C7:E9')const primaryCell = fWorksheet.getRange('D8').getRange()const disposable = fRange2.highlight( { stroke: 'red', fill: 'yellow', }, { ...primaryCell, actualRow: primaryCell.startRow, actualColumn: primaryCell.startColumn, },)// Remove the range C7:E9 highlight after 5 secondssetTimeout(() => { disposable.dispose()}, 5000)Split text into columns
FRange.splitTextToColumns splits the text in the range into columns using the specified delimiter.
The first example uses the default delimiter:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// A1:A3 has following values:// A |// 1,2,3 |// 4,,5,6 |const fRange = fWorksheet.getRange('A1:A3')fRange.setValues([['A'], ['1,2,3'], ['4,,5,6']])// After calling splitTextToColumns(true), the range will be:// A | |// 1 | 2 | 3// 4 | 5 | 6fRange.splitTextToColumns(true)// After calling splitTextToColumns(false), the range will be:// A | | |// 1 | 2 | 3 |// 4 | | 5 | 6fRange.splitTextToColumns(false)The second example passes a semicolon and a comma:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// A1:A3 has following values:// A |// 1;;2;3 |// 1;,2;3 |const fRange = fWorksheet.getRange('A1:A3')fRange.setValues([['A'], ['1;;2;3'], ['1;,2;3']])// After calling splitTextToColumns(false, univerAPI.Enum.SplitDelimiterType.Semicolon|univerAPI.Enum.SplitDelimiterType.Comma), the range will be:// A | | |// 1 | | 2 | 3// 1 | | 2 | 3fRange.splitTextToColumns(false, univerAPI.Enum.SplitDelimiterType.Semicolon | univerAPI.Enum.SplitDelimiterType.Comma)// After calling splitTextToColumns(true, univerAPI.Enum.SplitDelimiterType.Semicolon|univerAPI.Enum.SplitDelimiterType.Comma), the range will be:// A | |// 1 | 2 | 3// 1 | 2 | 3fRange.splitTextToColumns(true, univerAPI.Enum.SplitDelimiterType.Semicolon | univerAPI.Enum.SplitDelimiterType.Comma)The third example passes a custom delimiter:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// A1:A3 has following values:// A |// 1#2#3 |// 4##5#6 |const fRange = fWorksheet.getRange('A1:A3')fRange.setValues([['A'], ['1#2#3'], ['4##5#6']])// After calling splitTextToColumns(false, univerAPI.Enum.SplitDelimiterType.Custom, '#'), the range will be:// A | | |// 1 | 2 | 3 |// 4 | | 5 | 6fRange.splitTextToColumns(false, univerAPI.Enum.SplitDelimiterType.Custom, '#')// After calling splitTextToColumns(true, univerAPI.Enum.SplitDelimiterType.Custom, '#'), the range will be:// A | |// 1 | 2 | 3// 4 | 5 | 6fRange.splitTextToColumns(true, univerAPI.Enum.SplitDelimiterType.Custom, '#')Get the coordinates of the range
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')console.log(fRange.getCellRect()) // width、heigh、left、right、top、bottom、x、yGet the merge information and coordinates of the range at the same time
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')console.log(fRange.getCell())Cell events and editing
The following examples cover pointer, rendering, editing, and clipboard interactions. For all events and payload types, see Events Reference. In plugin mode, import @univerjs/sheets-ui/facade before subscribing; the Sheets Core preset includes it. Dispose subscriptions when the owning component or page is removed.
Usage example
addEvent registers a listener for any event. The basic form is:
import '@univerjs/sheets-ui/facade'const subscription = univerAPI.addEvent(univerAPI.Event.CellClicked, ({ row, column }) => { console.log(row, column)})// Call subscription.dispose() when the owning component or page is removed.Cell PointerMove event
CellPointerMove fires when the mouse moves over a cell and reports which cell is under the pointer.
univerAPI.addEvent(univerAPI.Event.CellPointerMove, (params) => { // Get event parameters const { worksheet, workbook, row, column } = params console.log('Current cell position:', worksheet.getRange(row, column).getA1Notation())})Cell PointerDown event
CellPointerDown fires when a mouse button is pressed on a cell.
univerAPI.addEvent(univerAPI.Event.CellPointerDown, (params) => { const { worksheet, workbook, row, column } = params console.log('Mouse down cell:', worksheet.getRange(row, column).getA1Notation())})Cell PointerUp event
CellPointerUp fires when the mouse button is released on a cell.
univerAPI.addEvent(univerAPI.Event.CellPointerUp, (params) => { const { worksheet, workbook, row, column } = params console.log('Mouse up cell:', worksheet.getRange(row, column).getA1Notation())})Cell Hover event
CellHover fires when the mouse hovers over a cell.
univerAPI.addEvent(univerAPI.Event.CellHover, (params) => { const { worksheet, workbook, row, column } = params console.log('Hovered cell:', worksheet.getRange(row, column).getA1Notation())})Cell DragOver event
DragOver fires when an element is dragged over a cell.
univerAPI.addEvent(univerAPI.Event.DragOver, (params) => { const { worksheet, workbook, row, column } = params console.log('Drag over cell:', worksheet.getRange(row, column).getA1Notation())})Cell Drop event
Drop fires when an element is dropped onto a cell.
univerAPI.addEvent(univerAPI.Event.Drop, (params) => { const { worksheet, workbook, row, column } = params console.log('Drop target cell:', worksheet.getRange(row, column).getA1Notation())})Cell Click event
CellClicked fires when a cell is clicked.
univerAPI.addEvent(univerAPI.Event.CellClicked, (params) => { const { worksheet, workbook, row, column } = params console.log('Clicked cell:', worksheet.getRange(row, column).getA1Notation())})Custom cell rendering
registerCellCustomRender installs the custom renderers used when cells are drawn.
Example 1 uses fixed-position rendering. Adding rows does not move the drawn content:
// Fixed position renderinguniverAPI.registerCellCustomRender([ { drawWith: (ctx, info, skeleton, spreadsheets) => { const { row, col } = info // Render a checkmark at position (1,1) if (row === 1 && col === 1) { const { primaryWithCoord } = info const { startX, startY } = primaryWithCoord ctx.fillText('✅', startX, startY + 10) } }, },])// Refresh canvas to apply renderinguniverAPI.getActiveWorkbook().getActiveSheet().refreshCanvas()Example 2 uses marker-based rendering. The drawing moves with its row and column:
// Set markeruniverAPI .getActiveWorkbook() .getActiveSheet() .getRange('B2') .setValue({ custom: { key: 'needCheck' } })// Render based on markeruniverAPI.registerCellCustomRender([ { drawWith: (ctx, info, skeleton, spreadsheets) => { const { row, col, data } = info // Render checkmark at marked position if (data?.custom?.key === 'needCheck') { const { primaryWithCoord } = info const { startX, startY } = primaryWithCoord ctx.fillText('✅', startX, startY + 10) } }, },])// Refresh canvas to apply renderinguniverAPI.getActiveWorkbook().getActiveSheet().refreshCanvas()Cell editing events
Start editing
const fWorkbook = univerAPI.getActiveWorkbook()fWorkbook.startEditing()End editing
// Pass true to commit changes, false to cancel editing// This is an async function, requires awaitconst fWorkbook = univerAPI.getActiveWorkbook()await fWorkbook.endEditingAsync(true)Start editing event
BeforeSheetEditStart fires before cell editing begins.
univerAPI.addEvent(univerAPI.Event.BeforeSheetEditStart, (params) => { const { worksheet, workbook, row, column, eventType, keycode } = params console.log('Before cell edit:', params) // If you want to prevent entering the editing state params.cancel = true})SheetEditStarted fires when cell editing starts.
const disposable = univerAPI.addEvent(univerAPI.Event.SheetEditStarted, (params) => { const { worksheet, workbook, row, column, eventType, keycode } = params console.log(params)})// Remove the event listener, use `disposable.dispose()`End editing event
BeforeSheetEditEnd fires before cell editing ends.
const disposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetEditEnd, (params) => { const { worksheet, workbook, row, column, value, eventType, keycode, isConfirm } = params console.log(params) // Cancel the cell edit end operation params.cancel = true})// Remove the event listener, use `disposable.dispose()`SheetEditEnded fires after cell editing ends.
univerAPI.addEvent(univerAPI.Event.SheetEditEnded, (params) => { const { worksheet, workbook, row, column, eventType, keycode, isConfirm } = params console.log('After cell edit:', params)})Clipboard events
BeforeClipboardChange
BeforeClipboardChange fires before the clipboard content changes. It can be used to inspect or modify that content before the change occurs.
univerAPI.addEvent(univerAPI.Event.BeforeClipboardChange, (params) => { const { text, html } = params console.log('Clipboard content:', text, html) // If you want to cancel the clipboard change // params.cancel = true;})BeforeClipboardPaste
BeforeClipboardPaste fires before content is pasted. It can be used to inspect or modify the content before it is pasted.
univerAPI.addEvent(univerAPI.Event.BeforeClipboardPaste, (params) => { const { text, html } = params console.log('Content to paste:', text, html) // If you want to cancel the paste operation // params.cancel = true;})ClipboardChanged
ClipboardChanged fires after the clipboard content has changed.
univerAPI.addEvent(univerAPI.Event.ClipboardChanged, (params) => { const { text, html } = params console.log('New clipboard content:', text, html)})ClipboardPasted
ClipboardPasted fires after content has been pasted.
univerAPI.addEvent(univerAPI.Event.ClipboardPasted, (params) => { const { text, html } = params console.log('Pasted content:', text, html)})Cell editing troubleshooting
How to get the data in the cell editor in real time?
Subscribe to SheetEditChanging to read the current rich-text value while a cell is being edited. The value remains in the editor and is written to the worksheet only when editing finishes.
import '@univerjs/sheets-ui/facade'const subscription = univerAPI.addEvent(univerAPI.Event.SheetEditChanging, ({ value }) => { console.log(value.toPlainText())})// Call subscription.dispose() when the owning component or page is removed.When the cell editor is focused and an external button is clicked to trigger an event, the snapshot obtained does not contain the data of the focused cell.
Cell data is synchronized to the snapshot when the cell editor loses focus, that is, when editing ends. The cell must therefore lose focus before the snapshot is read. Editing can be ended explicitly as follows:
import '@univerjs/sheets-ui/facade'async function saveWorkbook() { const fWorkbook = univerAPI.getActiveWorkbook() if (!fWorkbook) return await fWorkbook.endEditingAsync(true) const snapshot = fWorkbook.save() console.log(snapshot)}$btn.addEventListener('click', () => { saveWorkbook().catch(console.error)})Reference: https://github.com/dream-num/univer/issues/1314
Wait for the Rendered or Steady stage
Many APIs require the interface to be fully rendered before they work. A call made immediately after a Workbook is created may not take effect. Perform such calls in the Rendered or Steady stage of the lifecycle:
const disposable = univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => { if (stage === univerAPI.Enum.LifecycleStages.Steady) { // code... }})// To remove the event listener, you can call `disposable.dispose()`Reference: Lifecycle
How is this guide?