Other API Samples

Live SpreadsheetGear API Samples

Shapes Picture

Add a picture from an image file to a worksheet.

// Create a new workbook and get a reference to the active worksheet, cells and 
// window info.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.ActiveWorksheet;
SpreadsheetGear.IRange cells = worksheet.Cells;
SpreadsheetGear.IWorksheetWindowInfo windowInfo = worksheet.WindowInfo;

// Set up the image file name.
string filename = "SG-Picture.png";

// Get the width and height of the picture in pixels and convert to
// points for use in the call to AddPicture.  This step is only
// necessary if the actual picture size is to be used and that size
// is unknown.  Another option is to calculate the width and height 
// in row and column coordinates in the same manner as the left 
// and top are calculated in the code below.
double width;
double height;
System.Drawing.Image image = System.Drawing.Image.FromFile(filename);
using (image)
    width = image.Width * 72.0 / image.HorizontalResolution;
    height = image.Height * 72.0 / image.VerticalResolution;

// Calculate the left and top coordinates of the picture by converting 
// row and column coordinates to points.  Use fractional values to 
// get coordinates anywhere in between row and column boundaries.
double left = windowInfo.ColumnToPoints(0.25);
double top = windowInfo.RowToPoints(1.5);

// Add the picture from the file's bytes and use the calculated bounds.
byte[] imageBytes = System.IO.File.ReadAllBytes(filename);
SpreadsheetGear.Shapes.IShape shape =
    worksheet.Shapes.AddPicture(imageBytes, left, top, width, height);

// Remove the border around the picture shape.
shape.Line.Visible = false;

// Select the picture.
Run This Sample
Render Image

Generate an image representation of the results of this sample, which uses the SpreadsheetGear.Drawing.Image class to convert ranges, charts and shapes to images.

Download File

Download an Excel Open XML Workbook (*.xlsx) file with the results of this sample.

Supporting Files

The following files are utilized by this sample: