Formas
Las formas en Univer Sheets se pueden usar para crear diagramas de flujo, anotaciones, llamadas y guías visuales directamente en hojas de trabajo.
Modo de complemento
Instalación
pnpm add @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-uinpm install @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-uiyarn add @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-uibun add @univerjs-pro/engine-formula @univerjs/drawing @univerjs/drawing-ui @univerjs/sheets-drawing @univerjs/sheets-drawing-ui @univerjs-pro/sheets-shape @univerjs-pro/sheets-shape-uiLas formas también requieren UniverProFormulaEnginePlugin del paquete @univerjs-pro/engine-formula. En el código de inicialización base, sustituya la importación y el registro de UniverFormulaEnginePlugin por este plugin. No registre ambos motores de fórmulas, ya que la inserción de formas podría fallar por una dependencia no registrada.
Los complementos de formas dependen de los complementos de dibujo. También debe registrar UniverDrawingPlugin, UniverSheetsDrawingPlugin, UniverDrawingUIPlugin y UniverSheetsDrawingUIPlugin antes de registrar los complementos de formas.
Uso
import { UniverProFormulaEnginePlugin } from '@univerjs-pro/engine-formula'import { UniverSheetsShapePlugin } from '@univerjs-pro/sheets-shape'import { UniverSheetsShapeUIPlugin } from '@univerjs-pro/sheets-shape-ui'import SheetsShapeUIEnUS from '@univerjs-pro/sheets-shape-ui/locale/en-US'import { LocaleType, mergeLocales, Univer } from '@univerjs/core'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-pro/sheets-shape/facade'import '@univerjs/drawing-ui/lib/index.css'import '@univerjs/sheets-drawing-ui/lib/index.css'import '@univerjs-pro/sheets-shape-ui/lib/index.css'const univer = new Univer({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( DrawingUIEnUS, SheetsDrawingUIEnUS, SheetsShapeUIEnUS, ), },})univer.registerPlugin(UniverProFormulaEnginePlugin)univer.registerPlugin(UniverDrawingPlugin)univer.registerPlugin(UniverDrawingUIPlugin)univer.registerPlugin(UniverSheetsDrawingPlugin)univer.registerPlugin(UniverSheetsDrawingUIPlugin)univer.registerPlugin(UniverSheetsShapePlugin)univer.registerPlugin(UniverSheetsShapeUIPlugin)Si tiene una licencia comercial para Univer, consulte Uso de la licencia en Client para la configuración.
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.
| Paquete | Registro de escritorio | Registro móvil |
|---|---|---|
@univerjs/drawing-ui | UniverDrawingUIPlugin | UniverDrawingMobileUIPlugin |
@univerjs/sheets-drawing-ui | UniverSheetsDrawingUIPlugin | UniverSheetsDrawingMobileUIPlugin |
@univerjs-pro/sheets-shape-ui | UniverSheetsShapeUIPlugin | UniverSheetsShapeMobileUIPlugin |
Modo preestablecido
La función de forma está incluida en el ajuste preestablecido @univerjs/preset-sheets-advanced. Este ajuste preestablecido ya registra UniverProFormulaEnginePlugin, por lo que no es necesario sustituir manualmente el motor de fórmulas.
Instalación
El ajuste preestablecido UniverSheetsAdvancedPreset de @univerjs/preset-sheets-advanced depende del UniverSheetsDrawingPreset preestablecido en tiempo de ejecución. Primero instale @univerjs/preset-sheets-drawing.
pnpm add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advancednpm install @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advancedyarn add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advancedbun add @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advancedUso
import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced'import UniverPresetSheetsAdvancedEnUS from '@univerjs/preset-sheets-advanced/locales/en-US'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'import '@univerjs/preset-sheets-advanced/lib/index.css'const { univerAPI } = createUniver({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales( UniverPresetSheetsCoreEnUS, UniverPresetSheetsDrawingEnUS, UniverPresetSheetsAdvancedEnUS, ), }, presets: [ UniverSheetsCorePreset(), UniverSheetsDrawingPreset(), UniverSheetsAdvancedPreset(), ],})Si tiene una licencia comercial para Univer, consulte Uso de licencia en el cliente para la configuración.
API de Facade
Las definiciones completas del tipo de API de Facade se pueden encontrar en FacadeAPI.
Importar
Plugin mode note
Sólo el modo complemento requiere importar manualmente el paquete Facade. El modo Preestablecido ya incluye el paquete Fachada correspondiente, por lo que no se necesita ninguna importación adicional.
import '@univerjs-pro/sheets-shape/facade'Insertar formas básicas
Llama a FWorksheet.insertShape con los datos de creación comunes. Devuelve una fachada activa.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const rectShape = fWorksheet.insertShape({ shapeType: univerAPI.Enum.ShapeTypeEnum.Rect, transform: { left: 120, top: 80, width: 240, height: 120 }, shapeData: { fill: { fillType: univerAPI.Enum.ShapeFillEnum.SolidFill, color: '#e6f4ff', }, stroke: { lineStrokeType: univerAPI.Enum.ShapeLineTypeEnum.SolidLine, color: '#1677ff', width: 2, }, },})if (!rectShape) throw new Error('Shape could not be inserted.')Editar el texto de una forma
Utiliza la forma devuelta por insertShape() a continuación o en el ejemplo anterior. getText() devuelve un objeto FShapeText activo. Lee el texto con getPlainText(), reemplázalo por completo con setText() y configura la fuente, el color y la alineación.
if (!rectShape) throw new Error('Shape is not available')const shapeText = rectShape.getText()console.log(shapeText.getPlainText())shapeText .setText('Quarterly review') .setFontSize(18) .setColor('#2563eb') .setBold(true) .setHorizontalAlign(univerAPI.Enum.HorizontalAlign.CENTER) .setVerticalAlign(univerAPI.Enum.VerticalAlign.MIDDLE)setText() reemplaza el texto existente. Utiliza setRichText() para combinar varios estilos. Para editar texto enriquecido existente, llama a getRichText()?.copy(), modifica el constructor y pásalo a setRichText(). Los cambios del constructor no se aplican automáticamente. Consulta también los estilos de texto y los márgenes y la disposición del cuadro de texto.
const richText = univerAPI.newRichText() .text('Quarterly ') .bold('review')shapeText.setRichText(richText)Inserte y conecte formas de conector
Inserta un conector con FWorksheet.insertShape y vincula sus extremos mediante la fachada FConnectorShape devuelta.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const leftShape = fWorksheet.insertShape({ shapeType: univerAPI.Enum.ShapeTypeEnum.RoundRect, transform: { left: 80, top: 80, width: 180, height: 100 },})const rightShape = fWorksheet.insertShape({ shapeType: univerAPI.Enum.ShapeTypeEnum.Ellipse, transform: { left: 420, top: 200, width: 180, height: 100 },})const connectorShape = fWorksheet.insertShape({ shapeType: univerAPI.Enum.ShapeTypeEnum.BentConnector3, transform: { left: 240, top: 130, width: 240, height: 120 },})if (!leftShape || !rightShape || !connectorShape) { throw new Error('Shapes could not be inserted.')}const startSite = leftShape.getConnectionSites()[0]const rightSites = rightShape.getConnectionSites()const endSite = rightSites[2] ?? rightSites[0]if (!startSite || !endSite) throw new Error('Connection site not found.')connectorShape .bindStart(leftShape.getId(), startSite.index) .bindEnd(rightShape.getId(), endSite.index) .setEndArrow(univerAPI.Enum.ShapeArrowTypeEnum.Arrow)Actualizar y eliminar formas
Actualiza y elimina una forma directamente mediante su fachada activa.
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const firstShape = fWorksheet.getShapes().find(shape => !shape.isConnectorShape())if (firstShape) { firstShape .setStrokeColor('#ff4d4f') .setStrokeWidth(3) .setSolidFill('#fff1f0') // Remove the shape later if needed const removed = firstShape.remove() console.log(removed)}Copiar formato de formas
Selecciona la forma original, activa el pincel y elige la forma de destino. Se copian relleno, contorno, efectos y formato de texto compatible, conservando identidad, geometría, contenido y vínculos de fórmulas del destino. Borrar formato restaura los valores de inserción. SmartArt queda excluido. El plugin UI correspondiente registra esta función automáticamente.
¿Cómo es esta guía?