Rango y selección y celda
Esta página describe rangos, selecciones y celdas. Explica cómo leer y escribir valores a través de un rango, cómo controlar la selección, y cómo manejar los eventos punteros, editados y portapapeles.
- Rango
- Selección
- Operaciones avanzadas con rangos
- Eventos y edición de celdas
- Solución de problemas de edición
Rango
Un rango es un área rectangular de una hoja de trabajo. Se puede definir por la fila de inicio y la columna junto con el número de filas y columnas, o por la fila y columna de inicio junto con la fila final y la columna.
La mayoría de las operaciones de hoja de cálculo se realizan a través de la API de rango: valores de configuración y lectura, estilos de configuración y de lectura, etc.
Para las definiciones de tipo completas de las API de gama, vea FRange FacadeAPI.
Crear un rango
Un rango requiere una fila inicial, una columna inicial y un tamaño.
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())Un rango también se puede describir en la notación A1, con un nombre de hoja de trabajo opcional en frente:
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())Obtener datos de rango
Lea la célula superior izquierda de un rango:
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) devuelve un objeto de texto rico. Las células vacías devuelven null o undefined; las células normales devuelven una cadena, número o booleano. Llame a toPlainText() sólo en un objeto de contenido rico.
Leer cada valor en el rango:
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))Lea todas las fórmulas en el rango:
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 rangeEstablecer valor de rango
Establecer un valor único
Pasando un valor o un objeto celular sobrescribe cada célula en el rango. Una cadena que comienza con = se interpreta como una fórmula.
Por ejemplo, el siguiente código establece todos los A1:B2 a Hello, Univer:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange.setValue('Hello, Univer')El siguiente código establece C1 a =A1+B1, por lo que el resultado aparece fuera de las celdas de entrada:
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')Un objeto celular puede ser pasado en su lugar:
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')fRange.setValue({ v: 'Hello, Univer', custom: { key: 'value', },})An ICellData objeto que suministra v o p sin f y si Sustituye la fórmula existente y su identidad de forma compartida. f sin si También separa la célula de su fórmula compartida anterior. Un parche que lleva sólo el estilo o campos personalizados preserva la fórmula. Escribir v no aclara texto rico, por lo que incluir p: null cuando un valor reemplaza el texto rico. Las mismas reglas se aplican a los objetos celulares pasados a setValues().
Para configurar sólo la célula superior izquierda de la gama, utilice FRange.setValueForCell:
fRange.setValueForCell('Hello, Univer')Establezca múltiples valores con una matriz
El array debe coincidir con la altura y la anchura de la gama.
Las entradas pueden ser valores claros o objetos celulares.
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' }],])Establezca múltiples valores con un objeto
Cuando se pasa un objeto, la llave de nivel superior es el número de fila y la llave anida es el número columna. El rango no necesita coincidir con el tamaño del objeto.
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', },})Borrar datos del rango
FRange.clearaclara el contenido y el formato de la gama.FRange.clearContentsolo aclara el contenido.FRange.clearFormatsolo aclara el formato.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorkSheet = fWorkbook.getActiveSheet()const fRange = fWorkSheet.getRange('A1:D10')// Clears content and formatting information of the range.fRange.clear()Obtener estilo de rango
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 rangeEstablecer estilo de rango
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')Borrar estilo de rango
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)Aplicar el pincel de formato a filas y columnas
Seleccione las celdas que llevan el formato a copiar, active el pintor de formato, y luego haga clic o arrastre los encabezados de filas o encabezados de columnas para aplicar el formato a filas o columnas enteras. También se pueden seleccionar las células de destino en la rejilla.
Selección
Navegación de teclas de flecha, animación de selección, la manija de llenado, y arrastrar las indicaciones de sobreescritura se describen en selección y ajustes de arrastración.
Univer Sheets admite múltiples áreas de selección, por lo que una selección es una variedad de rangos, y estos rangos se manipulan a través de la API de rango.
Las API también están disponibles para obtener la selección actual, establecer la selección y escuchar cambios en la selección.
Para las definiciones de tipo completo de las API de selección, vea FSelection FacadeAPI.
Obtener selección activa
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:B2Establecer selección
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'))Obtener celda actual
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()) // B11Desactivar/activar/ocultar/mostrar selección
Una selección deshabilitada deja de responder a la entrada. transparentSelection esconde la selección en su lugar. A diferencia de disableSelection, la selección sigue siendo funcional; sólo es invisible.
const fWorkbook = univerAPI.getActiveWorkbook()// Disable selectionfWorkbook.disableSelection()// Enable selectionfWorkbook.enableSelection()// Hide selectionfWorkbook.transparentSelection()// Show selectionfWorkbook.showSelection()Escuche los cambios de selección
univerAPI.addEvent(univerAPI.Event.SelectionChanged, (params) => { const { worksheet, workbook, selections } = params console.log(params)})Celda
Los datos de células se almacenan en la hoja de trabajo como un mapa bidimensional, donde el primer índice es el número de fila y el segundo es el número columna.
A continuación se muestra un objeto celular típico:
const data = { v: 'Hello, Univer', s: 'styleId', t: CellValueType.STRING,}Para las descripciones completas del campo, consulte Configurar datos de células.
Es bueno saberlo
- Una operación celular es una operación de rango en una fila de gama alta y una columna de ancho. Las capacidades de un rango se describen en Rango.
- El plugin Univer API también almacena atributos de células extendidas en la propiedad
resourcesde laWorkbook. Ver Modelo personalizado de plugin
Operaciones avanzadas con rangos
Insertar celdas
FRange.insertCells inserta las células vacías en el rango. Los datos existentes en la hoja se desplazan lejos del rango insertado a lo largo de la dimensión especificada.
// 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]]Eliminar celdas
FRange.deleteCells elimina las células del rango. Los datos existentes en la hoja se desplazan hacia el rango eliminado a lo largo de la dimensión especificada.
// 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]]Fusionar celdas
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();Resaltar rango
FRange.highlight destaca el rango con el estilo especificado y la célula primaria.
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)Dividir el texto en columnas
FRange.splitTextToColumns divide el texto en el rango en columnas usando el delimitador especificado.
El primer ejemplo utiliza el delimitador predeterminado:
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)El segundo ejemplo pasa un semicollón y una coma:
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)El tercer ejemplo pasa un delimitador personalizado:
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, '#')Obtener las coordenadas del rango
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、yObtener la información de combinación y coordenadas del rango al mismo tiempo
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')console.log(fRange.getCell())Eventos y edición de celdas
Los siguientes ejemplos cubren las interacciones de puntero, renderizado, edición y portapapeles. Para todos los eventos y tipos de carga, vea Referencia de eventos. En modo plugin, importar @univerjs/sheets-ui/facade antes de suscribirse; el preset de Hojas Core lo incluye. Desarrollar suscripciones cuando se elimina el componente o página de propiedad.
Ejemplo de uso
addEvent registra un oyente para cualquier evento. La forma básica es:
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.Evento Cell PointerMove
CellPointerMove se dispara cuando el ratón se mueve sobre una célula e informa que célula está bajo el puntero.
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())})Evento Cell PointerDown
CellPointerDown se dispara cuando se presiona un botón del ratón en una celda.
univerAPI.addEvent(univerAPI.Event.CellPointerDown, (params) => { const { worksheet, workbook, row, column } = params console.log('Mouse down cell:', worksheet.getRange(row, column).getA1Notation())})Evento Cell PointerUp
CellPointerUp se dispara cuando el botón del ratón se libera en una celda.
univerAPI.addEvent(univerAPI.Event.CellPointerUp, (params) => { const { worksheet, workbook, row, column } = params console.log('Mouse up cell:', worksheet.getRange(row, column).getA1Notation())})Evento Cell Hover
CellHover se dispara cuando el ratón pasa por una celda.
univerAPI.addEvent(univerAPI.Event.CellHover, (params) => { const { worksheet, workbook, row, column } = params console.log('Hovered cell:', worksheet.getRange(row, column).getA1Notation())})Evento Cell DragOver
DragOver dispara cuando un elemento se arrastra sobre una célula.
univerAPI.addEvent(univerAPI.Event.DragOver, (params) => { const { worksheet, workbook, row, column } = params console.log('Drag over cell:', worksheet.getRange(row, column).getA1Notation())})Evento de caída de celda
Drop dispara cuando un elemento se deja caer en una celda.
univerAPI.addEvent(univerAPI.Event.Drop, (params) => { const { worksheet, workbook, row, column } = params console.log('Drop target cell:', worksheet.getRange(row, column).getA1Notation())})Evento de clic en celda
CellClicked se dispara cuando se hace clic en una celda.
univerAPI.addEvent(univerAPI.Event.CellClicked, (params) => { const { worksheet, workbook, row, column } = params console.log('Clicked cell:', worksheet.getRange(row, column).getA1Notation())})Evento de renderizado de celda
registerCellCustomRender instala los renderizadores personalizados utilizados cuando se dibujan las células.
Ejemplo 1 utiliza la renderización de posición fija. La adición de filas no mueve el contenido dibujado:
// 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()Ejemplo 2 utiliza la renderización basada en marcadores. El dibujo se mueve con su fila y columna:
// 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()Eventos de edición de celda
Iniciar edición
const fWorkbook = univerAPI.getActiveWorkbook()fWorkbook.startEditing()Finalizar edición
// Pass true to commit changes, false to cancel editing// This is an async function, requires awaitconst fWorkbook = univerAPI.getActiveWorkbook()await fWorkbook.endEditingAsync(true)Evento de inicio de edición
BeforeSheetEditStart dispara antes de que comience la edición de celdas.
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 dispara cuando comienza la edición de celdas.
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()`Evento de finalización de edición
BeforeSheetEditEnd dispara antes de que termine la edición de celdas.
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 se dispara después de que termine la edición celular.
univerAPI.addEvent(univerAPI.Event.SheetEditEnded, (params) => { const { worksheet, workbook, row, column, eventType, keycode, isConfirm } = params console.log('After cell edit:', params)})Eventos del portapapeles
Antes del cambio del portapapeles
BeforeClipboardChange se dispara antes de que el contenido del portapapeles cambie. Se puede utilizar para inspeccionar o modificar ese contenido antes de que ocurra el cambio.
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 dispara antes de que se pega el contenido. Se puede utilizar para inspeccionar o modificar el contenido antes de que sea pegado.
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 se dispara después de que el contenido del portapapeles haya cambiado.
univerAPI.addEvent(univerAPI.Event.ClipboardChanged, (params) => { const { text, html } = params console.log('New clipboard content:', text, html)})ClipboardPasted
ClipboardPasted dispara después de que el contenido haya sido pegado.
univerAPI.addEvent(univerAPI.Event.ClipboardPasted, (params) => { const { text, html } = params console.log('Pasted content:', text, html)})Solución de problemas de edición
¿Cómo obtener los datos en el editor de celdas en tiempo real?
Suscríbete a SheetEditChanging para leer el valor actual de texto rico mientras se está editando una célula. El valor permanece en el editor y está escrito a la hoja de trabajo sólo cuando se termina la edición.
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.Cuando el editor de celdas está enfocado y se hace clic en un botón externo para activar un evento, la instantánea obtenida no contiene los datos de la celda enfocada.
Los datos de la célula se sincronizan con la instantánea cuando el editor de la célula pierde el enfoque, es decir, cuando finaliza la edición. La célula debe perder el foco antes de que se lea la instantánea. La edición puede terminarse explícitamente como sigue:
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)})Referencia: https://github.com/dream-num/univer/issues/1314
Esperar a la etapa Rendered o Steady
Muchas API requieren que la interfaz se renderice completamente antes de que funcionen. Una llamada hecha inmediatamente después de que se crea un libro de trabajo puede no tener efecto. Realizar tales llamadas en la etapa Rendered o Steady del ciclo de vida:
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()`Referencia: Ciclo de vida
¿Cómo es esta guía?