officefileapi-115447-excel-export-library-pictures-how-to-insert-and-position-a-picture-in-a-worksheet.md
This topic describes how to use the Excel Export Library to insert a picture into a worksheet. The IXlPicture interface contains properties and methods that allow you to load a picture from a file or stream, specify picture position, and add a hyperlink to the picture.
Follow the steps below to add a picture to a worksheet:
You can also use the IXlPicture.AnchorType, IXlPicture.TopLeft, and IXlPicture.BottomRight properties to specify or modify the anchor type and position of the picture’s anchors.
Note
When you finish working with the IXlPicture object, call the Dispose method to release all the resources used by the object. Otherwise, generated content is not written to the output file. You can also modify the IXlPicture object within the using statement ( Using block in Visual Basic).
The example below uses the IXlPicture.SetTwoCellAnchor method to anchor a picture to two cells in a worksheet. The anchor for the picture’s top-left corner is located at the intersection of the column “B” and the second row, with no offsets. The anchor for the picture’s bottom-right corner is located at the intersection of the column “G” and the twelfth row, with offsets from both the column and row. The IXlPicture.AnchorBehavior is set to XlAnchorType.TwoCell.
// Create a worksheet.
using (IXlSheet sheet = document.CreateSheet()) {
// Insert a picture from a file and anchor it to two cells.
using (IXlPicture picture = sheet.CreatePicture()) {
picture.SetImage(Image.FromFile(Path.Combine(imagesPath, "image1.jpg")), ImageFormat.Jpeg);
picture.SetTwoCellAnchor(new XlAnchorPoint(1, 1, 0, 0), new XlAnchorPoint(6, 11, 2, 15), XlAnchorType.TwoCell);
}
}
' Create a worksheet.
Using sheet As IXlSheet = document.CreateSheet()
' Insert a picture from a file and anchor it to two cells.
Using picture As IXlPicture = sheet.CreatePicture()
picture.SetImage(Image.FromFile(Path.Combine(imagesPath, "image1.jpg")), ImageFormat.Jpeg)
picture.SetTwoCellAnchor(New XlAnchorPoint(1, 1, 0, 0), New XlAnchorPoint(6, 11, 2, 15), XlAnchorType.TwoCell)
End Using
End Using
The following image shows the result (the workbook is opened in Microsoft® Excel®):
The IXlPicture interface contains the StretchToCell and FitToCell methods that allow you to resize a picture to fit a worksheet cell.
Use the StretchToCell method to stretch a picture so that it fills the entire cell. If cell size changes, the picture size changes accordingly.
Use the FitToCell method to scale a picture proportionally to fit a cell of the specified size. The method’s last parameter specifies whether to center the picture in the cell.
See Also