2
votes

I am inserting an image in an excel cell, but usually that image will be larger, both in height and in width than the original cell. So after I have inserted my image I would like to: resize the specific excel row and column according to the image's size. This is what I have:

        Microsoft.Office.Interop.Excel.Application xlApp;
        Microsoft.Office.Interop.Excel.Worksheet ws;
        object misValue = System.Reflection.Missing.Value;
        xlApp = new Microsoft.Office.Interop.Excel.Application();
        Workbook wb = xlApp.Workbooks.Open(@".../MyExcelFile.xlsx");
        ws = wb.Sheets[1];

        string picPath = @"..../MyPic.png";

        System.Drawing.Image img = System.Drawing.Image.FromFile(picPath);
        var size = img.Size;

        Microsoft.Office.Interop.Excel.Range oRange = (Microsoft.Office.Interop.Excel.Range)ws.Cells[1, 5];
        float Left = (float)((double)oRange.Left);
        float Top = (float)((double)oRange.Top);
        const float ImageSize = 32;
        ws.Shapes.AddPicture(picPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);

So here I am inserting my image in the 5th cell of the 1st row, but setting its size to 32.However, I have access to this image's height and width. How can I set row 1 to that height and column 5 to that width?

EDIT: With the current code from Richard Mneyan, it looks like this, so the image doesn't fit in the cell: enter image description here

1

1 Answers

2
votes

The below would set height and width of your cell to respective picture height and width if you apply ratio of Column widths to Row Heights:

    var sh = ws.Shapes.AddPicture(picPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);
    oRange.Rows[1].RowHeight = sh.Height;
    oRange.Columns[1].ColumnWidth = sh.Width;

This is not perfect answer because it is really hard to set Excel Column Widths to exact number. For instance the default Excel Column width is 8.43, the next increment would be 8.57. Why?; because it is based on number of the Normal font characters that can fit in a cell: https://support.microsoft.com/en-us/help/214123/description-of-how-column-widths-are-determined-in-excel

Here applying approximate ratios (which is not perfect):

        double rColRow = 6; // Ratio of units of measure: columns widths to row heights
        double rImgColWidth = 5.9; // Ratio of units of measure: image size and column widths

        oRange.Rows[1].RowHeight = (sh.Width * rColRow / rImgColWidth);
        oRange.Columns[1].ColumnWidth = (sh.Height / rImgColWidth);