I’m currently using this code to add an image to a cell. This works as expected
var imageStream = new MemoryStream(mydata);
sheet.Pictures.Add(imageStream, ExcelPictureFormat.Png, cell.Name, cell.Name);
As it bounds to the full cell, it loses the ratio, as it attaches top-left and bottom-right of the cell. Is there an option to bind it to top-left and top-right so that height ratio is kept?
Hi! GemBox.Spreadsheet doesn’t support binding to top-left and top-right of a cell. I am not sure that that is even possible in Excel.
Hi,
Try this:
var picture = sheet.Pictures.Add("image.png", cell.Name);
double ratio = picture.Position.Width / picture.Position.Height;
picture.Position.Width = cell.Column.GetWidth(LengthUnit.Point);
picture.Position.Height = picture.Position.Width / ratio;
Does this solve your issue?
Regards,
Mario
Hi Mario
Thanks, this is not really what I’m looking for, because the image will the overflow the cell
This is the code I’m currently using, similar to yours, but also changing the row height.
var imgWidth = img.ImageWidth;
var imgHeight = img.ImageHeight;
var cellWidth = cell.Column.GetWidth(LengthUnit.Pixel);
var cellHeight = cell.Row.GetHeight(LengthUnit.Pixel);
var height = (int)(cellWidth * imgHeight / imgWidth);
cell.Row.SetHeight(height, LengthUnit.Pixel);
var imageStream = new MemoryStream(img.ImageData.ToArray());
var picture = sheet.Pictures.Add(imageStream, ExcelPictureFormat.Png, cell.Name, cellWidth, height, LengthUnit.Pixel);
If you want to set the cell into a single cell without changing the cell’s size (column width and row height) then check the second example on the following page:
Thanks, but also you are setting the height in that example
// Create a sheet with specified columns width and rows height.
for (int i = 0; i < 6; i++)
{
worksheet.Columns[i].SetWidth(10 * (i + 1), LengthUnit.Point);
worksheet.Rows[i].SetHeight(10 * (i + 1), LengthUnit.Point);
}
The point of the example is that you have a cell with a predefined size and you’re fitting the image into it and keeping the image’s aspect ratio.
That loop is to create cells with different sizes, and then the example adds an image to each of those cells.
1 Like