Imágenes

Las imágenes se pueden usar para enriquece el contenido de la hoja de cálculo, mejora la expresión visual y ayuda a ilustrar o resaltar información clave.

Actualmente, los tipos de imágenes admitidos son: imágenes flotantes e imágenes de celdas.

Modo predeterminado

Instalación

Shell
pnpm add @univerjs/preset-sheets-drawing

Uso

TypeScript
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US'import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'import UniverPresetSheetsDrawingEnUS from '@univerjs/preset-sheets-drawing/locales/en-US'import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'import '@univerjs/preset-sheets-core/lib/index.css'import '@univerjs/preset-sheets-drawing/lib/index.css'const { univerAPI } = createUniver({  locale: LocaleType.EN_US,  locales: {    [LocaleType.EN_US]: mergeLocales(      UniverPresetSheetsCoreEnUS,      UniverPresetSheetsDrawingEnUS,     ),  },  presets: [    UniverSheetsCorePreset(),    UniverSheetsDrawingPreset(),   ],})

Si está utilizando la función Colaboración, asegúrese de pasar la opción collaboration: true en UniverSheetsDrawingPreset:

TypeScript
UniverSheetsDrawingPreset({  collaboration: true, })

Preajustes y configuración

TypeScript
interface IUniverSheetsDrawingPresetConfig {  /**   * Whether use the collaboration feature.   * @default false   */  collaboration?: boolean  /**   * The maximum allowed size of uploaded images in bytes.   * @default 5 * 1024 * 1024 (5MB)   */  allowImageSize?: number}

Modo de complemento

Instalación

Shell
pnpm add @univerjs/docs-drawing @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui

Uso

TypeScript
import { IImageIoService, LocaleType, mergeLocales, Univer } from '@univerjs/core'import { UniverDocsDrawingPlugin } from '@univerjs/docs-drawing'import { UniverDrawingPlugin } from '@univerjs/drawing'import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui'import DrawingUIEnUS from '@univerjs/drawing-ui/locale/en-US'import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing'import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui'import SheetsDrawingUIEnUS from '@univerjs/sheets-drawing-ui/locale/en-US'import '@univerjs/drawing-ui/lib/index.css'import '@univerjs/sheets-drawing-ui/lib/index.css'import '@univerjs/sheets-drawing/facade'import '@univerjs/sheets-drawing-ui/facade'const univer = new Univer({  locale: LocaleType.EN_US,  locales: {    [LocaleType.EN_US]: mergeLocales(      DrawingUIEnUS,       SheetsDrawingUIEnUS,     ),  },})univer.registerPlugin(UniverDrawingPlugin)univer.registerPlugin(UniverDrawingUIPlugin)univer.registerPlugin(UniverSheetsDrawingPlugin)univer.registerPlugin(UniverSheetsDrawingUIPlugin)

Si está utilizando la función Colaboración, debe agregar la configuración override:

TypeScript
univer.registerPlugin(UniverDrawingPlugin, {  override: [[IImageIoService, null]],   // allowImageSize: 20 * 1024 * 1024, // set the maximum allowed size of uploaded images to 20MB, optional})

Complementos y Configuración

TypeScript
interface IUniverDrawingConfig {  /**   * The maximum allowed size of uploaded images in bytes.   * @default 5 * 1024 * 1024 (5MB)   */  allowImageSize?: number}

Compatibilidad móvil

Configure primero el editor móvil. En la inicialización en modo plugin de esta página, sustituya los registros de escritorio siguientes por las exportaciones móviles de los mismos paquetes antes de abrir un documento. Conserve modelos, estilos, traducciones e importaciones Facade; no registre ambas variantes.

PaqueteRegistro de escritorioRegistro móvil
@univerjs/drawing-uiUniverDrawingUIPluginUniverDrawingMobileUIPlugin
@univerjs/sheets-drawing-uiUniverSheetsDrawingUIPluginUniverSheetsDrawingMobileUIPlugin

API de fachada

Las definiciones completas del tipo de API de Facade se pueden encontrar en FacadeAPI.

Importación

Plugin mode note

Solo el modo complemento requiere importar manualmente el paquete Facade. El modo preestablecido ya incluye el paquete Facade correspondiente, por lo que no se necesita ninguna importación adicional.

TypeScript
import '@univerjs/sheets-drawing/facade'import '@univerjs/sheets-drawing-ui/facade'

Agregar DOM flotante

El método FWorksheet.addFloatDomToPosition(layer) puede agregar un elemento DOM flotante a una posición específica.

TSX
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// You should register components at an appropriate time (e.g., when Univer is loaded)// This is a React component. For Vue3 components, the third parameter should be `{ framework: 'vue3' }`univerAPI.registerComponent(  'myFloatDom',  ({ data }) => (    <div style={{ width: '100%', height: '100%', background: '#fff', border: '1px solid #ccc', boxSizing: 'border-box' }}>      popup content:      {' '}      {data?.label}    </div>  ),)// Add a floating DOM// If disposable is null, floating DOM addition failedconst disposable = fWorksheet.addFloatDomToPosition({  componentKey: 'myFloatDom',  initPosition: {    startX: 100,    endX: 300,    startY: 100,    endY: 200,  },  // Component data  data: {    label: 'hahah',  },})// 2 秒后移除浮动 DOMsetTimeout(() => {  disposable?.dispose()}, 2000)

El método FWorksheet.addFloatDomToRange(range, layer, domLayout) puede agregar un elemento DOM flotante a un rango específico.

TSX
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// Register a range loading componentfunction 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:C3const fRange = fWorksheet.getRange('A1:C3')const disposable = fWorksheet.addFloatDomToRange(fRange, { componentKey: 'RangeLoading' }, {}, 'myRangeLoading')// Remove the floating DOM after 2 secondssetTimeout(() => {  disposable?.dispose()}, 2000)// another example-------------------// Register a float button componentfunction FloatButton() {  const divStyle = {    width: '100px',    height: '30px',    backgroundColor: '#fff',    border: '1px solid #ccc',    boxSizing: 'border-box' as const,    display: 'flex',    justifyContent: 'center',    alignItems: 'center',    textAlign: 'center' as const,    cursor: 'pointer',  }  const clickHandler = () => {    console.warn('click')  }  return (    <div style={divStyle} onClick={clickHandler}>      FloatButton    </div>  )}univerAPI.registerComponent('FloatButton', FloatButton)// Add the float button to the range A5:C7, position is start from A5 cell, and width is 100px, height is 30px, margin is 100% of range width and heightconst fRange2 = fWorksheet.getRange('A5:C7')const disposable2 = fWorksheet.addFloatDomToRange(  fRange2,  {    componentKey: 'FloatButton',  },  {    width: 100,    height: 30,    marginX: '100%', // margin percent to range width, or pixel    marginY: '100%',  },  'myFloatButton',)

El método FWorksheet.addFloatDomToColumnHeader(column, layer, domPos) puede agregar un elemento DOM flotante a una columna específica encabezado.

TSX
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()// Register a float button componentfunction FloatButton() {  const divStyle = {    width: '100px',    height: '30px',    backgroundColor: '#fff',    border: '1px solid #ccc',    boxSizing: 'border-box' as const,    display: 'flex',    justifyContent: 'center',    alignItems: 'center',    textAlign: 'center' as const,    cursor: 'pointer',  }  const clickHandler = () => {    console.warn('click')  }  return (    <div style={divStyle} onClick={clickHandler}>      FloatButton    </div>  )}univerAPI.registerComponent('FloatButton', FloatButton)// Add the float button to the column D header, position is right align, width is 100px, height is 30px, margin is 0const disposable = fWorksheet.addFloatDomToColumnHeader(  3,  {    componentKey: 'FloatButton',    allowTransform: false,  },  {    width: 100,    height: 30,    marginX: 0,    marginY: 0,    horizonOffsetAlign: 'right',  },  'myFloatButton',)// Remove the float button after 2 secondssetTimeout(() => {  disposable?.dispose()}, 2000)

Insertar imágenes flotantes

FWorksheet.newOverGridImage() crea un generador de imágenes flotantes, devuelve una instancia de FOverGridImageBuilder y genera un objeto ISheetImage para insertar imágenes flotantes a través de llamadas en cadena.

Aquí hay algunos métodos de miembros en FOverGridImageBuilder:

MétodoDescripción
buildAsyncConstruya la imagen y devuelva el objeto ISheetImage
setSourceEstablezca el origen de la imagen
setColumnEstablezca la posición horizontal de la imagen
setRowEstablezca la posición vertical de la imagen
setColumnOffsetEstablezca el desplazamiento horizontal de la imagen
setRowOffsetEstablezca el desplazamiento vertical de la imagen
setWidthEstablecer el ancho de la imagen
setHeightEstablecer el alto de la imagen
setAnchorTypeEstablezca el tipo de anclaje de la imagen, ya sea que la posición y el tamaño cambien con la celda
setCropTopEstablezca la región de recorte de la imagen definiendo los bordes superiores, mostrando así la parte específica de la imagen que desea
setCropLeftEstablezca la región de recorte de la imagen definiendo los bordes izquierdos, mostrando así la parte específica de la imagen que desea
setCropBottomEstablezca la región de recorte de la imagen definiendo los bordes inferiores, mostrando así la parte específica de la imagen que desea
setCropRightEstablezca el recortar la región de la imagen definiendo los bordes derechos, mostrando así la parte específica de la imagen que desea
setRotateEstablecer el ángulo de rotación de la imagen
TypeScript
// create a new image builder and set image source.// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300pxconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const image = await fWorksheet.newOverGridImage()  .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)  .setColumn(5)  .setRow(5)  .setWidth(500)  .setHeight(300)  .buildAsync()fWorksheet.insertImages([image])

También puede insertar imágenes mediante el método FWorksheet.insertImage(url, column, row, offsetX, offsetY).

TypeScript
// Insert an image to the sheet, position is F6, offset is 10pxconst fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const result = await fWorksheet.insertImage('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', 5, 5, 10, 10)

Obtener imágenes flotantes

El método FWorksheet.getImages() puede obtener todas las imágenes flotantes en la hoja de trabajo y devolver una matriz de FOverGridImage[] instancias.

TypeScript
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const images = fWorksheet.getImages()images.forEach((image) => {  image.getId()})

También puede obtener una imagen flotante por su ID usando el método FWorksheet.getImageById(id).

Actualizar imágenes flotantes

El método FWorksheet.updateImages(sheetImages) puede actualizar la posición y el tamaño de las imágenes flotantes. etc.

TypeScript
// create a new image builder and set image source.// then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 500px, height is 300pxconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const image = await fWorksheet.newOverGridImage()  .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)  .setColumn(5)  .setRow(5)  .setWidth(500)  .setHeight(300)  .buildAsync()fWorksheet.insertImages([image])// update the image width to 100px and height to 50px after 4 secondssetTimeout(async () => {  const imageBuilder = fWorksheet.getImageById(image.drawingId).toBuilder()  const newImage = await imageBuilder.setWidth(100).setHeight(50).buildAsync()  fWorksheet.updateImages([newImage])}, 4000)

Eliminar imágenes flotantes

El método FWorksheet.deleteImages(sheetImages) puede eliminar imágenes flotantes.

TypeScript
const fWorksheet = univerAPI.getActiveWorkbook().getActiveSheet()const image = fWorksheet.getImages()[0]// Delete the first image of the sheetfWorksheet.deleteImages([image])

Insertar imágenes de celdas

El método FRange.insertCellImageAsync(file) puede insertar imágenes de celdas.

TypeScript
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// Insert an image into the cell A10const fRange = fWorksheet.getRange('A10')const result = await fRange.insertCellImageAsync('https://avatars.githubusercontent.com/u/61444807?s=48&v=4')

Imagen de fondo de la hoja

Una hoja puede mostrar una imagen repetida detrás de las celdas. Se almacena en IWorksheetData.backgroundImage, aparte de imágenes flotantes o de celda. El preset Drawing incluye esta función. En modo plugin necesitas @univerjs/sheets-drawing, su Facade y Drawing UI para renderizado y carga.

TypeScript
import '@univerjs/sheets-drawing/facade'const sheet = univerAPI.getActiveWorkbook()?.getActiveSheet()if (!sheet) throw new Error('No active worksheet')sheet.setBackgroundImage('https://example.com/background.png')console.log(sheet.getBackgroundImage())sheet.deleteBackgroundImage()

setBackgroundImage() usa ImageSourceType.URL por defecto y reemplaza el fondo; deleteBackgroundImage() lo elimina. Ambas operaciones admiten deshacer/rehacer. La UI usa el servicio de imágenes configurado. El fondo es decorativo y no se imprime.

Opacidad de las imágenes

Las imágenes flotantes admiten opacidad global. setOpacity() acepta un número finito entre 0 (transparente) y 1 (opaco), con 1 como valor predeterminado; los valores inválidos provocan RangeError. Puede configurarse en FOverGridImageBuilder antes de crear la imagen o en un FOverGridImage existente. Ambos exponen getOpacity(). El panel de propiedades también permite ajustar la transparencia.

TypeScript
const sheet = univerAPI.getActiveWorkbook()?.getActiveSheet()const image = sheet?.getImages()[0]if (image) {  image.setOpacity(0.5)  console.log(image.getOpacity())}

Tamaño y anclaje de imágenes

Las imágenes insertadas con el selector integrado conservan la proporción y se reducen si hace falta para caber en 500 × 500 píxeles, sin ampliar imágenes pequeñas. El tamaño visible es distinto del límite de bytes allowImageSize. Con el Facade puedes indicar las dimensiones.

SheetDrawingAnchorType.Position se mueve con las celdas sin cambiar de tamaño, Both sigue posición y tamaño del rango, y None fija ambos. Ocultar y mostrar filas o columnas conserva los anclajes: las imágenes ligadas al tamaño del rango pueden reducirse temporalmente y recuperarse al mostrarlo. No sobrescribas los anclajes con esa geometría temporal.

¿Cómo es esta guía?

© 2026 DreamNum Co., Ltd.