Skip to content

Images and drawings ​

A drawing object is a Drawing handle, and Picture, Chart, Shape and Slicer are its subclasses; charts share the members below, and chart content is covered in Charts. The APIs expose their stored metadata and media bytes; they do not render drawings.

What you can do ​

Image information ​

formulon.getImageInfo(bytes) recognizes PNG, JPEG, GIF, and BMP bytes and returns ImageFormat plus pixel dimensions. It reads no workbook, so it lives on the formulon object (Python formulon.get_image_info(data)).

Finding drawings ​

ws.listDrawings() lists the handles of pictures, charts, shapes, groups, connectors, and other anchored objects; ws.drawing(objectId) returns one. The handle is an instance of the class its kind selects, and the sheet keeps one handle per object id, so every lookup returns the same object.

To narrow to one kind:

ToCall
Look up one objectws.picture(id), ws.chart(id), ws.shape(id) or ws.slicer(id)
List one kindws.listPictures(), listCharts(), listShapes() or listSlicers()

A lookup fails in these cases:

ConditionResult
A missing idStatusCode.NotFound
An object of another kindStatusCode.InvalidArgument

Reading a drawing ​

MemberReads or does
drawing.getDrawingProperties()DrawingProperties: objectId, kind, name, description, hidden, and the anchor (DrawingAnchor: kind, editAs, fromRow, fromCol, toRow, toCol, the four offsets and widthEmu / heightEmu, in EMU, English Metric Units; 12,700 per point), the same for every kind
picture.getProperties()PictureProperties: { format, widthPx, heightPx, bytes, rotationDeg, flipH, flipV }, a copy of the picture's media with its rotation and flips; the rotation reads as stored, so -90 reads -90. Fails with StatusCode.NotFound when the media part is missing
drawing.sheet, objectId, kindThe hosting sheet, the object's id in its drawing, and its kind. They stay readable after the object is removed
drawing.nameThe object's current name, read each time

Adding a picture ​

ws.addPicture(bytes, { name, description, hidden, anchor }) returns the Picture. bytes is anything load accepts: a Uint8Array, an ArrayBuffer or another view.

anchor is a one-cell or two-cell anchor with the keys kind, editAs, fromRow, fromCol, offsets, toRow, toCol, widthEmu and heightEmu. A one-cell picture results when kind is left out. Existing absolute anchors can be read through getDrawingProperties, but this API cannot insert an absolute anchor.

editAs (an AnchorEditAs; left out it is the anchor's own kind) controls how a two-cell picture follows edits. A zero width or height uses the probed pixel size in EMU.

One-cell anchorABC123fromB2:C3: the extent from widthEmuand heightEmuB2: the from cell plus the offsets
Placed by
The from cell and its offsets; widthEmu and heightEmu give the size.
Keys
fromRow, fromCol, the offsets, widthEmu, heightEmu
Inserted by addPicture
Yes. A picture added without a kind is one-cell; a zero width or height uses the image's pixel size.
update throws InvalidArgument for
  • A to* key
  • An absolute kind

Removing a drawing ​

ws.removeDrawing(objectOrId) removes a picture, chart, shape or slicer frame, leaves the other drawing objects, and throws StatusCode.NotFound for an unknown id. Unused media is removed when no object references it.

Removing the last object of a sheet's drawing, by any removal or by a row or column delete, also removes the drawing part and the sheet's link to it, as Excel does.

One-cell and two-cell picture anchors update with row and column insertions and deletions. A row or column delete that covers every row, or every column, of an object that moves and sizes with cells removes the object, as Excel does, together with any part only it used. This applies to pictures, charts, shapes, connectors, groups, form controls and OLE objects, in .xlsx and .xlsb.

Once an object is removed, every member of its handle but sheet, objectId and kind throws StatusCode.NotFound.

Updating a drawing ​

update(patch) is one member of every drawing handle (Picture, Chart, Shape, Slicer). Its keys are:

KeyEffect
nameRenames the object
descriptionnull or an empty string removes it
hiddenHides or shows the object
anchorMerges per key, as below

A key left out is unchanged, and no other key accepts null.

The anchor merges per key. An omitted key keeps the current value and an omitted kind keeps the object's kind, while a given kind converts the anchor. An object stored with an absolute anchor keeps it, whether or not the patch restates kind: AnchorKind.Absolute. For an absolute anchor the offsets set its position from A1 and the size its extent, in .xlsx and .xlsb; a one-cell or two-cell kind converts it.

The anchor getDrawingProperties() reads can be passed back unchanged: a two-cell anchor takes its box and ignores the size, a one-cell anchor takes the size.

An update fails in these cases:

ConditionResult
A non-zero fromRow or fromCol on an absolute anchorStatusCode.InvalidArgument; nothing changes
An absolute kind on any other anchorStatusCode.InvalidArgument; nothing changes
A to* key on a one-cell anchorStatusCode.InvalidArgument
A size on a two-cell anchorStatusCode.InvalidArgument
slicer.update({ name })StatusCode.PreconditionFailed, because a slicer's name ties the drawing frame to the slicer parts

Picture.update, Shape.update and Slicer.update also take their own keys, and apply the common keys first. A picture's own keys are:

KeyEffect
rotationDegStored as given to 1/60000 degree; 0 removes it
flipH, flipVfalse removes the flip

A rotation that is not finite or lies beyond about ±35791 degrees throws StatusCode.InvalidArgument, and a rotation change alone never moves the anchor. Python spells the keys rotation_deg, flip_h and flip_v.

Python's update(name=, description=, hidden=, anchor=) takes the anchor as a DrawingAnchorInput, as in picture.update(anchor=DrawingAnchorInput(from_row=2, from_col=0)).

Z-order and snapshots ​

setZOrder(index) and snapshot() are members of Picture, Chart and Shape. A Slicer has setZOrder; a slicer has no snapshot.

setZOrder(index) moves the object to an index of ws.listDrawings(), where 0 is the back and the last index is the top.

snapshot() captures an opaque, versioned byte string containing the object's list position, element, relationships, and media or chart parts. ws.restoreDrawing(bytes) replaces the object with the same id at its recorded position and returns its handle. It accepts { assignNewId: true } (Python assign_new_id=True) to add a copy on top with a fresh id. A snapshot can be restored into another sheet.

Parsed drawings are required, which includes drawings loaded from XLSB. A retained XLSB drawing the reader cannot lift reports StatusCode.IoDrawingUnparseable.

Drawing bindings ​

The C calls are fm_get_image_info, fm_sheet_get_drawing_object_count, fm_sheet_get_drawing_object_at, fm_sheet_get_picture, fm_sheet_add_picture, fm_sheet_remove_drawing, fm_sheet_update_drawing, fm_sheet_set_drawing_z_order, fm_sheet_snapshot_drawing, and fm_sheet_restore_drawing; they take the sheet index and object id that a handle carries. The renderer and hit testing remain outside this API.

Example ​

js
import createFormulon from '@libraz/formulon'

const formulon = await createFormulon()
using wb = formulon.Workbook.createDefault()
const ws = wb.sheet(0)
const png = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='), c => c.charCodeAt(0))

console.log(formulon.getImageInfo(png)) // { format: 1, widthPx: 1, heightPx: 1 }
const picture = ws.addPicture(png, { name: 'dot', anchor: { fromRow: 0, fromCol: 0 } })
console.log(picture.getProperties().bytes.length) // 68
const snapshot = picture.snapshot()
picture.update({ anchor: { fromRow: 2 } }) // other anchor keys are kept
console.log(picture.getDrawingProperties().anchor.fromRow) // 2
ws.removeDrawing(picture)
const restored = ws.restoreDrawing(snapshot) // same id, recorded position
console.log(restored.objectId === picture.objectId, restored.getDrawingProperties().anchor.fromRow) // true 0
const copy = ws.restoreDrawing(snapshot, { assignNewId: true }) // a new object on top
console.log(copy.objectId === restored.objectId, ws.listDrawings().length) // false 2
python
import formulon
from formulon import DrawingAnchorInput, DrawingPlacementInput, Workbook

png = bytes.fromhex('89504e470d0a1a0a0000000d4948445200000001000000010804000000b51c0c020000000b4944415478da6364f80f00010501012718e3660000000049454e44ae426082')
with Workbook.create_default() as wb:
    ws = wb[0]
    print(formulon.get_image_info(png))  # ImageInfo(format=<ImageFormat.PNG: 1>, width_px=1, height_px=1)
    picture = ws.add_picture(png, DrawingPlacementInput(name='dot', anchor=DrawingAnchorInput(from_row=0, from_col=0)))
    print(len(picture.get_properties().bytes))  # 68
    snapshot = picture.snapshot()
    picture.update(anchor=DrawingAnchorInput(from_row=2))  # other anchor keys are kept
    print(picture.get_drawing_properties().anchor.from_row)  # 2
    ws.remove_drawing(picture)
    restored = ws.restore_drawing(snapshot)  # same id, recorded position
    print(restored.object_id == picture.object_id, restored.get_drawing_properties().anchor.from_row)  # True 0
    copy = ws.restore_drawing(snapshot, assign_new_id=True)  # a new object on top
    print(copy.object_id == restored.object_id, len(ws.list_drawings()))  # False 2

Saving to XLSB ​

Pictures, charts, and shapes are written to XLSB as a sheet drawing. A drawing that also holds slicer frames, SmartArt, or other non-chart graphic frames is not linked.

Notes, their drawing, threaded comments and persons are written for each sheet and read back on load, and a note's formatted runs keep their fonts. A note without a revision id gets the one Excel assigns, built from the sheet's tab position and the note's place among that sheet's notes. A note created through the API has no revision id; editing a loaded note keeps its id.

deferredFeatureCount on the wb.saveWithDiagnostics(WorkbookFormat.Xlsb) result (Python save_with_diagnostics(format=...), deferred_feature_count) reports these omissions. An unlinked drawing counts once per sheet, not once per picture.

A drawing loaded from XLSB is listed and editable like an XLSX drawing; one the reader cannot lift is retained verbatim and passes through on save. See File formats for the full boundary. Legacy note text and regenerated comment VML geometry approximate Excel.

Pictures in cells ​

A picture placed in a cell, as Excel's Place in Cell does, is a value of its own kind: ValueKind.Picture (Python ValueKind.PICTURE, C FM_VALUE_KIND_PICTURE). Code that switches over every ValueKind needs a case for Picture.

Reading cell pictures ​

CallReturns
A tagged readA PictureValue whose pictureId names the picture (Python Value.picture_id, C fm_value_t.u.picture_id)
ws.getValue, toNativeAn ExcelPicture (Python to_native), which prints as [picture]
wb.getCellPicture(pictureId)The CellPicture of an id, or null when the workbook has no such picture (Python Workbook.get_cell_picture, C fm_workbook_get_cell_picture)
ws.getCellPicture(row, col) (or an A1 address)The picture of a cell directly, including one a formula produced or a spill member holds

A CellPicture is the ImageProperties of the image (format, widthPx, heightPx and bytes) plus altText, which is null when there is none. The id belongs to one workbook and still names its picture after the last cell holding it is cleared.

Placing a picture ​

ws.setCellPicture(row, col, { bytes, altText? }) places an image. ws.setValue(cell, picture) with an ExcelPicture or a PictureValue places the picture an id names, which copies a picture to another cell. Either write replaces a formula in the cell.

ws.setCellPicture(row, col, null) removes a placed picture and empties the cell; it does nothing to a formula cell or a spill member whose result is a picture.

A picture in the way of a spill, or in a cell of an array formula's range other than its anchor, blocks the formula and its anchor reads #SPILL!.

PNG and JPEG are stored as given, and bytes identical to a picture already in the workbook share its image. Trailing spaces of altText are removed, and an omitted, null or empty altText means none.

A write fails in these cases:

ConditionResult
An id the workbook has no picture forStatusCode.NotFound
Another format or empty bytesStatusCode.IoImageUnsupported
A picture over 32 MiBStatusCode.SecurityResourceLimit
setCellPicture on a workbook that keeps its rich values as stored (File formats)StatusCode.IoFeatureNotWritable, since that layout cannot take a new picture

A refused call leaves the cell as it was.

Python spells the calls get_cell_picture() and set_cell_picture(), takes a CellPictureInput(bytes, alt_text=None), a CellPicture read back, or None, and names the fields bytes, alt_text, format, width_px and height_px.

Formulas and saving ​

A formula that reads a picture cell returns the picture, so =A1 over a picture cell has this kind, as does an evaluation result that contains one. TYPE gives 128, ISERROR gives FALSE and COUNTA counts the cell. A function that needs a number or text from it, as A1&"x" does, gives #VALUE!.

.xlsx and .xlsb keep placed pictures and formula-result pictures, with their alt text; a picture whose media part is missing is saved as a plain #VALUE! cell. The remaining differences from Excel are listed under Remaining differences.

  • Comments and notes — threaded comments, people, and notes.
  • Shapes — drawing shapes, text boxes and connectors.
  • Slicers — table slicers.
  • Charts — read, create, and edit charts, and resolve their series against cell values.