Inserting an Image into a Cell

Introduction

Fitting a picture exactly to a single cell is a common requirement when designing spreadsheets that act as visual reports, product catalogs, employee directories, dashboards, or inventory lists. Rather than stretching an image across many cells or placing it loosely on a worksheet, you may want a clean, cell-bound image that stays aligned with the cell that owns it. Aspose.Cells supports this scenario in two complementary ways:

  • Approach 1 — Place a floating picture over a cell. Add a Picture to the worksheet, set its Placement to MoveAndSize, and adjust its anchor cells (UpperLeftRow, UpperLeftColumn, LowerRightRow, LowerRightColumn) so the picture covers exactly one cell.
  • Approach 2 — Embed an image directly in a cell. Assign image bytes to the cell’s EmbeddedImage property. The image automatically scales to fit the cell’s display area and travels with the cell. The rest of this article walks through both approaches, explains the relevant APIs, and shows how to use them in code.

Approach 1: Place a Picture Over a Cell

A floating picture is a Picture object that lives on the worksheet drawing layer. Although it is not part of any single cell, it is anchored to a cell range. The picture’s anchor cells — its upper-left and lower-right corners — determine its visual extent on the worksheet. By default, a freshly added picture spans several cells. To make a floating picture cover exactly one cell, you need to:

  1. Add the picture using worksheet.getPictures().add(int row, int column, InputStream stream), which anchors the new picture to the given cell.
  2. Set the four anchor properties so the picture’s bounding rectangle coincides with the target cell.
  3. Set picture.setPlacement(PlacementType.MOVE_AND_SIZE) so the picture moves and resizes with the underlying cell when the user changes the column width or row height.

Anchoring the Picture to a Single Cell

The picture’s anchor is defined by four zero-based index properties:

  • picture.setUpperLeftRow(int) — the row index of the picture’s top edge.
  • picture.setUpperLeftColumn(int) — the column index of the picture’s left edge.
  • picture.setLowerRightRow(int) — the row index of the picture’s bottom edge. To make the picture’s bottom edge sit at the bottom of row r, set this to r + 1.
  • picture.setLowerRightColumn(int) — the column index of the picture’s right edge. To make the picture’s right edge sit at the right of column c, set this to c + 1.