Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel image in a cell

How do I insert an image (of type Image) into a specific cell in a Excel sheet

taperSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item("Taper");

Microsoft.Office.Interop.Excel.Range cell = GetMyPictureCELL(taperSheet);

Image myImage = new Image();
RenderTargetBitmap bmp;

bmp = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myViewPort);

myImage.Source = bmp;
myImage.Stretch = Stretch.Uniform;

and now ? I was hoping for

cell.Add(myImage)

But I assume it is not that easy.

/Stefan

Thanks for your input doitgood

The following code works for me

In my case my Image source is a viewport (myViewPort) The placement of the image is determinated by cell

try
{
    Image myImage = new Image();
    RenderTargetBitmap bmp;
    PngBitmapEncoder encoder;
    string fileName;
    System.IO.Stream stream;
    object missing = System.Reflection.Missing.Value; 
    Microsoft.Office.Interop.Excel.Picture pic = null;
    Microsoft.Office.Interop.Excel.Pictures p = null;

    bmp = new RenderTargetBitmap((int)this.Width, (int)this.Height, 96, 96, PixelFormats.Pbgra32);
    bmp.Render(myViewPort);

    myImage.Source = bmp;
    myImage.Stretch = Stretch.Uniform;

    fileName = System.IO.Path.GetTempFileName();
    stream = System.IO.File.OpenWrite(fileName);

    encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    encoder.Save(stream);
    stream.Close();

    p = taperSheet.Pictures(missing) as Microsoft.Office.Interop.Excel.Pictures; 
    pic = p.Insert(fileName, missing); 
    pic.Left = cell.Left;
    pic.Top = cell.Top;

}
catch { }
like image 223
Stefan Olsson Avatar asked Sep 14 '11 08:09

Stefan Olsson


People also ask

Can you embed a picture in a cell in Excel?

Click the location in your worksheet where you want to insert a picture. On the Insert ribbon, click Pictures. Select This Device… Browse to the picture you want to insert, select it, and then click Open.


1 Answers

Try this:

object missing = System.Reflection.Missing.Value;
Excel.Range picPosition = GetPicturePosition(); // retrieve the range for picture insert
Excel.Pictures p = yourWorksheet.Pictures(missing) as Excel.Pictures;
Excel.Picture pic = null;
pic = p.Insert(yourImageFilePath, missing);
pic.Left = Convert.ToDouble(picPosition .Left);
pic.Top = Convert.ToDouble(picPosition .Top);
pic.Placement = // Can be any of Excel.XlPlacement.XYZ value

And don't forget to release all that stuff!

like image 176
Benoit Drapeau Avatar answered Oct 08 '22 14:10

Benoit Drapeau