1

I am downloading an image from a URL and saving to the local drive, in C:\Temp directory.

I am able to ADD a picture to a worksheet using the following code:

System.Drawing.Image img = System.Drawing.Image.FromFile(strFileLocation);

Excel.Shape shapeAdd = wsNew.Shapes.AddPicture(strFileLocation, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 400, 100 * jPageItemNumber, img.Width, img.Height);
shapeAdd.Name = "Item" + jPageItemNumber.ToString() + "_Pic2";

However, what I really want to do is CHANGE the picture of an existing shape instead of adding a new one.

I have this code, which does not throw an error, but also does absolutely nothing:

Excel.Shape shpPicture = getShape(wsNew, "Item" + jPageItemNumber.ToString() + "_Pic");
shpPicture.Fill.UserPicture(strFileLocation);

public static Excel.Shape getShape(Excel.Worksheet ws, string strShapeName)
{
    foreach (Excel.Shape s in ws.Shapes)
    {
        if (s.Name == strShapeName)
        {
            return s;
        }
    }
    return null;
}

What am I doing wrong here? I can find countless examples of ADDING pictures but no examples of CHANGING pictures in Excel.

Also, if it matters, I'd like to "fix" the proportions so they are not changed during this process and skew the picture I'm adding.

So just to make this more interesting, I have the following code in the same project. This code CREATES a NEW shape, THEN fills it with a UserPicture. Virtually the same code, only difference I see is that in this case I'm using a newly-created shape instead of an existing one. And this one DOES WORK.

Excel.Shape shapeStaticMap = wsNew2.Shapes.AddShape(Office.MsoAutoShapeType.msoShapeRectangle, 60, 75, 700, 500);
shapeStaticMap.Fill.UserPicture(strFileLocation);
gotmike
  • 1,515
  • 4
  • 20
  • 44
  • The answer is here: http://stackoverflow.com/questions/10169011/using-vba-to-change-picture - Is there any reason not to close this as a duplicate? – Jeremy Thompson Aug 03 '16 at 03:46
  • @JeremyThompson - That link is for VBA... how is it duplicate? – gotmike Aug 03 '16 at 12:06
  • Because the object model in Excel is 99% equivalently programmed via C# and Interop. Its a neat trick "record a macro" of what you want to do in VBA and convert it to C#, it's the same!! Please see some of my other answers around this topic. Easiest is just delete and recreate to change the pic. Good luck! – Jeremy Thompson Aug 03 '16 at 12:13
  • @JeremyThompson - okay, so i tried that and yes i can get it to work if i delete and create a new one... but see my updated question... if i create a NEW shape, i can use the exact same method to add a UserPicture fill to the shape, i just can't do that with an existing shape... does that make sense? – gotmike Aug 04 '16 at 11:18

0 Answers0