-
-
Notifications
You must be signed in to change notification settings - Fork 22
Adding an embedded image
An image must first be embedded into the spreadsheet before it can be used in a worksheet.
To embed an image, call Spreadsheet.EmbedImageAsync(Stream stream)
with the Stream
being the source image. This method must be called before the first call to Spreadsheet.StartWorksheetAsync
. This is to achieve good performance by avoiding the need of keeping another copy of the image in memory. EmbedImageAsync
streams the image directly into the resulting XLSX file, while also some required metadata about the image is being read. The method returns an EmbeddedImage
object which is then used later when referencing the image in a worksheet. Only PNG images are currently supported.
To use the image in a worksheet, call Spreadsheet.AddImage(ImageCanvas canvas, EmbeddedImage image)
. The ImageCanvas
parameter is used for placement and size of the image. Create an ImageCanvas
by calling one of its static methods, e.g. ImageCanvas.OriginalSize("B3")
which would place the image in its original size with its upper left corner at cell B3.
Note: When running on .NET Framework you might need to call e.g. ImageCanvas.OriginalSize("B3".AsSpan())
instead.
await using var spreadsheet = await Spreadsheet.CreateNewAsync(outputStream);
var embeddedImage = await spreadsheet.EmbedImageAsync(imageStream);
await spreadsheet.StartWorksheetAsync("Sheet");
var canvas = ImageCanvas.OriginalSize("B3");
spreadsheet.AddImage(canvas, embeddedImage);
await spreadsheet.FinishAsync();