Skip to main content
You are viewing help content for pre-release software. This document and the features it describes are subject to change.
All docs
V26.2
  • Create and Manage Shapes

    • 13 minutes to read

    The Spreadsheet Document API allows you to add shapes to Excel worksheets. You can create preset and custom shapes, specify shape position and appearance, add text to shapes, and group shapes.

    The following preset shape geometries are available:

    • Basic shapes: rectangles, ovals, triangles, and other simple geometric shapes
    • Block arrows
    • Equation shapes: plus, minus, multiply, equal, and not equal signs
    • Stars and banners
    • Callouts
    • Flowchart shapes

    A worksheet can also contain pictures, connectors, and shape groups. Pictures support additional scenarios, such as in-cell placement.

    Refer to the following help topics for additional information:

    Shape API Basics

    The Worksheet.Shapes collection stores drawing objects in a worksheet. The collection can contain the following objects:

    The following code snippet casts collection items to specific drawing object types:

    Shape shape = (Shape)worksheet.Shapes[0];
    PictureShape picture = (PictureShape)worksheet.Shapes[1];
    GroupShape group = (GroupShape)worksheet.Shapes[2];
    

    Position and Size a Shape

    The ShapeBase.ShapeAnchor property gets shape position and size settings that correspond to the anchor type (ShapeAnchor.Type).

    Call the AsAbsoluteAnchor, AsCellAnchor, or AsTwoCellAnchor method to convert the anchor to the class that corresponds to the shape’s anchor type and access anchor-specific properties. Each method returns null if the shape has another anchor type.

    To change the anchor type, assign an AbsoluteAnchor, CellAnchor, or TwoCellAnchor object to the ShapeAnchor property.

    To access anchor-specific properties, call the ShapeAnchor.AsAbsoluteAnchor, ShapeAnchor.AsCellAnchor, or ShapeAnchor.AsTwoCellAnchor method. Each method returns null if the anchor type does not match.

    Anchor properties specify positions, offsets, and sizes in document units (1/300 of an inch). Row and column indexes are zero-based.

    Anchor Class Properties
    AbsoluteAnchor X and Y (or Location) specify the shape position. Width and Height (or Size) specify the shape size.
    CellAnchor TopLeftRowIndex and TopLeftColumnIndex specify the cell that contains the top-left shape corner. TopLeftXOffset and TopLeftYOffset specify the corner offset within the top-left cell. Width and Height (or Size) specify a fixed shape size.
    TwoCellAnchor TopLeftRowIndex, TopLeftColumnIndex, BottomRightRowIndex, and BottomRightColumnIndex get the cells that contain the top-left and bottom-right shape corners. TopLeftXOffset, TopLeftYOffset, BottomRightXOffset, and BottomRightYOffset get the corner offsets within the corner cells. Call the SetCorners method to specify corner cells and offsets.

    The following code snippet anchors an oval to cells B2 and E6 so that the oval moves and resizes with worksheet cells:

    Shape shape = worksheet.Shapes.AddShape(ShapeType.Oval, ShapeAnchorType.TwoCells);
    TwoCellAnchor anchor = shape.ShapeAnchor.AsTwoCellAnchor();
    anchor.SetCorners(1, 1, 5, 4);
    

    Create a Shape

    You can create preset shapes, shapes with custom geometry, picture shapes, and connectors.

    Create a Preset Shape

    To add a shape to a worksheet, call the ShapeCollection.AddShape(type, anchorType) method. Pass a ShapeType preset and, optionally, a ShapeAnchorType value. The anchor type specifies how spreadsheet applications reposition and resize the shape when a user inserts or deletes rows and columns:

    ShapeAnchorType Description
    Absolute The drawing object does not move or resize with worksheet cells.
    TopLeftCell The drawing object moves with the cell that contains the top-left object corner and does not resize.
    TwoCells The drawing object moves and resizes with the cells that contain the top-left and bottom-right object corners.

    The following code snippet adds a rounded rectangle shape to a worksheet and specifies the shape position, size, fill, and outline:

    using System.IO;
    using System.Drawing;
    using DevExpress.Docs.Office;
    using DevExpress.Docs.Spreadsheet;
    
    Directory.CreateDirectory("output");
    
    // Load a workbook from a file.
    using Workbook workbook = new Workbook(File.OpenRead("Document.xlsx"));
    
    // Access the first worksheet in the workbook.
    Worksheet worksheet = workbook.Worksheets[0];
    
    // Add a rounded rectangle shape with an absolute position and size.
    Shape shape = worksheet.Shapes.AddShape(ShapeType.RoundedRectangle);
    
    // Specify the shape position and size in document units (1/300 of an inch).
    AbsoluteAnchor anchor = shape.ShapeAnchor.AsAbsoluteAnchor();
    anchor.X = 300;
    anchor.Y = 150;
    anchor.Width = 900;
    anchor.Height = 450;
    
    shape.Fill = new SolidFill(Color.LightSkyBlue);
    shape.Outline = new LineStyle { Fill = new SolidFill(Color.SteelBlue), Width = 2 };
    
    using FileStream stream = File.Create(Path.Combine("output", "Document.xlsx"));
    workbook.Save(stream);
    

    Create a Shape with Custom Geometry

    To create a shape with custom geometry, add ShapePath objects to a ShapeGeometry object, pass the geometry to the ShapeType(geometry) constructor, and pass the created ShapeType value to the AddShape method. Each path consists of segments (lines, arcs, and Bezier curves).

    The following code snippet creates a square shape with custom geometry:

    ShapeGeometry geometry = new ShapeGeometry();
    ShapePath path = new ShapePath(200, 200, true);
    path.Segments.Add(new PathMove(0, 0));
    path.Segments.Add(new PathLine(0, 200));
    path.Segments.Add(new PathLine(200, 200));
    path.Segments.Add(new PathLine(200, 0));
    path.Segments.Add(new PathClose());
    geometry.Paths.Add(path);
    
    Shape shape = worksheet.Shapes.AddShape(new ShapeType(geometry));
    

    Create a Picture Shape

    Call the ShapeCollection.AddImage method to add a picture to a worksheet as a floating shape.

    Refer to the following help topic for additional information: Insert and Manage Pictures.

    Connect Shapes

    A connector is a straight, elbow, or curved line that links two shapes or pictures. To add a connector to a worksheet, create a ConnectorShape object and pass it to the Add method of the Worksheet.Shapes collection. Use ConnectorShape.StartShape and ConnectorShape.EndShape properties to specify the linked shapes. The ConnectorShape.Type property specifies the connector type.

    The following code snippet adds two rectangles to a worksheet and connects the rectangles with an elbow connector that ends with an arrowhead:

    using System.IO;
    using System.Drawing;
    using DevExpress.Docs.Office;
    using DevExpress.Docs.Spreadsheet;
    
    Directory.CreateDirectory("output");
    
    using var workbook = new Workbook();
    var worksheet = workbook.Worksheets[0];
    
    // Add two rectangles. Specify positions and sizes in document units (1/300 of an inch).
    var firstShape = worksheet.Shapes.AddShape(ShapeType.Rectangle);
    var firstAnchor = firstShape.ShapeAnchor.AsAbsoluteAnchor();
    firstAnchor.X = 300;
    firstAnchor.Y = 300;
    firstAnchor.Width = 600;
    firstAnchor.Height = 300;
    
    var secondShape = worksheet.Shapes.AddShape(ShapeType.Rectangle);
    var secondAnchor = secondShape.ShapeAnchor.AsAbsoluteAnchor();
    secondAnchor.X = 1500;
    secondAnchor.Y = 900;
    secondAnchor.Width = 600;
    secondAnchor.Height = 300;
    
    // Connect connection site 3 (right side) of the first rectangle to connection site 1 (left side) of the second rectangle.
    var connector = new ConnectorShape {
        StartShape = firstShape,
        StartShapeSiteIndex = 3,
        EndShape = secondShape,
        EndShapeSiteIndex = 1,
        Type = ConnectorShapeType.ElbowWithHandle,
        Outline = new LineStyle {
            Fill = new SolidFill(Color.SteelBlue),
            Width = 2,
            EndArrowType = ArrowType.TriangleArrow
        }
    };
    worksheet.Shapes.Add(connector);
    
    using var stream = File.Create(Path.Combine("output", "Document.xlsx"));
    workbook.Save(stream);
    

    Get and Customize Shapes

    Get Shapes of a Specific Type

    Call the following ShapeCollection methods to get drawing objects of a specific type from a worksheet:

    Method Description
    GetShapes Returns preset and custom shapes in the collection.
    GetImageShapes Returns picture shapes in the collection.
    GetShapeGroups Returns shape groups in the collection.

    These methods return top-level items in the collection. To access shapes in a group, use the GroupShape.Shapes property.

    Customize Shape Appearance and Behavior

    Use the following properties to customize shape appearance and behavior. ShapeBase, ShapeWithRotation, and ShapeWithEffects properties apply to all shape types (presets, custom shapes, pictures, connectors, and groups). StyledShape properties apply to presets, custom shapes, pictures, and connectors. FilledShape properties apply to presets, custom shapes, and pictures:

    Property Description
    ShapeBase.Name Specifies the shape name.
    ShapeBase.AlternativeText Specifies alternative text for accessibility tools.
    ShapeBase.Decorative Specifies whether assistive technologies can skip the shape.
    ShapeBase.Lock Locks the shape against move, resize, and other changes on a protected worksheet.
    ShapeBase.LockText Locks shape text against edits on a protected worksheet.
    ShapeBase.PrintObject Specifies whether the shape appears on a printout.
    ShapeWithRotation.RotationAngle Specifies the shape’s rotation angle in degrees.
    ShapeWithEffects.Effects Specifies visual effects (for example, glow or soft edges).
    FilledShape.Type Specifies shape geometry (a preset or custom geometry).
    FilledShape.Fill Specifies the shape fill (solid, gradient, pattern, picture, or no fill).
    StyledShape.Outline Specifies the shape outline fill, width, dash type, and other line settings.
    StyledShape.Style Specifies a theme-based quick style for the shape.

    Note

    Lock and LockText settings take effect in a protected worksheet.

    The following code snippet gets the first preset or custom shape in a worksheet and modifies the shape name, rotation angle, fill, and outline:

    Shape shape = worksheet.Shapes.GetShapes().ElementAt(0);
    shape.Name = "Callout1";
    shape.RotationAngle = 15;
    shape.Fill = new SolidFill(Color.Gold);
    shape.Outline = new LineStyle { Fill = new SolidFill(Color.DarkGoldenrod), Width = 1.5f };
    

    Add Text to a Shape

    Use the Shape.TextArea property to add and format text in a shape. To add plain text, assign a string to the TextArea.Text property. To format individual paragraphs and text runs, add TextParagraph objects to the TextArea.Paragraphs collection.

    The following code snippet removes existing paragraphs from a shape and adds two formatted paragraphs (a bold title and a colored value):

    TextParagraph titleParagraph = new TextParagraph();
    titleParagraph.Runs.Add(new TextRun("Q3 Revenue", new TextProperties { Bold = true, FontSize = 14 }));
    
    TextParagraph valueParagraph = new TextParagraph();
    valueParagraph.Runs.Add(new TextRun("$1.2M", new TextProperties { FontSize = 18, Fill = new SolidFill(Color.DarkGreen) }));
    
    shape.TextArea.Paragraphs.Clear(); // Remove existing paragraphs.
    shape.TextArea.Paragraphs.Add(titleParagraph);
    shape.TextArea.Paragraphs.Add(valueParagraph);
    

    Reorder Shapes

    The order of items in a ShapeCollection specifies the stacking order (Z-order) of drawing objects. The first item is at the back. Each next item overlaps previous items. Z-order methods of the GroupShape.Shapes collection reorder shapes within the group.

    Call the following methods to modify the stacking order:

    Method Description
    BringToFront(shape) Places the specified shape in front of other drawing objects in the collection.
    BringForward(shape) Moves the specified shape one level forward in the stacking order.
    SendToBack(shape) Places the specified shape behind other drawing objects in the collection.
    SendBackward(shape) Moves the specified shape one level backward in the stacking order.
    Move(shape, newIndex) Moves the specified shape to the specified position in the collection.

    Each method has an overload that accepts a shape index instead of a shape object (for example, BringToFront(index) and Move(oldIndex, newIndex)).

    The following code snippet adds three overlapping shapes to a worksheet and modifies the shape stacking order:

    using System.IO;
    using System.Drawing;
    using DevExpress.Docs.Office;
    using DevExpress.Docs.Spreadsheet;
    
    Directory.CreateDirectory("output");
    
    using Workbook workbook = new Workbook();
    Worksheet worksheet = workbook.Worksheets[0];
    
    // Add three overlapping shapes. Each new shape appears in front of previous shapes.
    Shape rectangle = worksheet.Shapes.AddShape(ShapeType.Rectangle);
    rectangle.Fill = new SolidFill(Color.LightSkyBlue);
    
    Shape oval = worksheet.Shapes.AddShape(ShapeType.Oval);
    oval.Fill = new SolidFill(Color.Gold);
    oval.ShapeAnchor.AsAbsoluteAnchor().X = 150;
    
    Shape star = worksheet.Shapes.AddShape(ShapeType.Star5);
    star.Fill = new SolidFill(Color.OrangeRed);
    star.ShapeAnchor.AsAbsoluteAnchor().X = 300;
    
    // Place the star behind other shapes.
    // The stacking order is: star, rectangle, oval.
    worksheet.Shapes.SendToBack(star);
    
    // Move the rectangle (index 1) one level forward: star, oval, rectangle.
    worksheet.Shapes.BringForward(1);
    
    // Place the oval behind other shapes: oval, star, rectangle.
    worksheet.Shapes.Move(oval, 0);
    
    using FileStream stream = File.Create(Path.Combine("output", "Document.xlsx"));
    workbook.Save(stream);
    

    Group Shapes

    You can group shapes to move, resize, and rotate them together. To add an empty GroupShape to a worksheet, call the ShapeCollection.AddShapeGroup(anchorType) method.

    The group position and size match the bounds of shapes in the group. If you move or resize the group, the group moves and scales grouped shapes.

    The following code snippet creates a group of two stars and rotates the group:

    GroupShape group = worksheet.Shapes.AddShapeGroup();
    
    Shape shape1 = group.Shapes.AddShape(ShapeType.Star12);
    shape1.Fill = new SolidFill(Color.Gold);
    
    Shape shape2 = group.Shapes.AddShape(ShapeType.Star10);
    shape2.Fill = new SolidFill(Color.OrangeRed);
    shape2.ShapeAnchor.AsAbsoluteAnchor().X = 400;
    
    group.RotationAngle = 10;
    

    Shapes in a group must have an absolute anchor (ShapeAnchorType.Absolute). If you add a shape with another anchor type to the GroupShape.Shapes collection, the API throws an ArgumentException.

    Note

    Do not add a shape to both the worksheet Shapes collection and a group to ensure that the worksheet does not contain two independent drawing objects for one shape (a standalone shape and a group member).

    If you remove a group from a worksheet, the worksheet also removes the shapes in the group.

    Remove Shapes

    To remove a drawing object from a worksheet, call the Remove or RemoveAt method of the Worksheet.Shapes collection. To find drawing objects of a specific type, call the GetShapes, GetImageShapes, or GetShapeGroups method. These methods return lazily evaluated sequences. Call the ToList method to copy a sequence before you modify the collection in a loop.

    The following code snippet removes all preset and custom shapes from a worksheet:

    foreach (Shape shape in worksheet.Shapes.GetShapes().ToList())
    {
        worksheet.Shapes.Remove(shape);
    }