How to add a picture to a worksheet in Word and Excel using VSTO with c# and autosize

Here is a really simple example of adding a picture without really needing to know the dimensions of the image. Excel uses points which is pretty annoying, since pics are in pixels….duh… I put in the sizes for my pics, but you could use any number since we repair it with the scale calls. Anyway, here it is. Word vstoDoc is my document.

[csharp]
//push resource to disk.
var path = Path.GetDirectoryName(vstoDoc.FullName);
var fn = Path.Combine(path,"rfn.png");
//insert the fun fact box at top.
var pic = vstoDoc.Shapes.AddPicture(fn,false,true,5,5,455/1.0,162/1.0);
pic.Name = ROLLFORWARDSHAPENAME;
pic.ScaleHeight(1, MsoTriState.msoTrue);
pic.ScaleWidth(1, MsoTriState.msoTrue);
[/csharp]

Here is Excel. vstoSheet is my Worksheet. I loop through them to add pics.

[csharp]
//push resource to disk.
var path = Path.GetDirectoryName(vstoDoc.FullName);
var fn = Path.Combine(path,"rfn.png");
var pic = vstoSheet.Shapes.AddPicture(fn, MsoTriState.msoFalse, MsoTriState.msoTrue, 5, 5, 231 * 72 / 96, 317 * 72 / 96);
pic.Name = ROLLFORWARDSHAPENAME;
pic.Locked = false;
pic.ScaleHeight(1, MsoTriState.msoTrue);
pic.ScaleWidth(1, MsoTriState.msoTrue);
[/csharp]

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *