Adding an image from a memory stream to an Excel document

I have an image in a memory stream, and I want to write it to an MS Excel document, the PIA only provides the AddPicture method, which takes the file path.

Is it possible to add an image without writing to disk?

MSDN

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.shapes.addpicture(v=office.14).aspx

+7
source share
1 answer

Well, a bit of blind flight, but assuming something about your code (e.g. the source of your stream, data type, etc.), this might be the solution:
First, you need to create bitmap data from a stream (which, I suppose, is a stream of bytes, also assuming the stream describes a bitmap). There is a solution already for this here on Stack Overflow: Byte array for bitmap
I will copy the code from the solution:

int w= 100; int h = 200; int ch = 3; //number of channels (ie. assuming 24 bit RGB in this case) 
byte[] imageData = new byte[whch]; //you image data here Bitmap bitmap = new Bitmap(w,h,PixelFormat.Format24bppRgb); BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); IntPtr pNative = bmData.Scan0; Marshal.Copy(imageData,0,pNative,whch); bitmap.UnlockBits(bmData);
Also suppose you have an object for your workbook and the worksheet that you are going to work with, something like this:
 xlBook = (Excel.Workbook)objExcel.Workbooks.Add(""); xlSheet = (Excel.Worksheet)xlBook.Worksheets 1 ; xlSheet.Activate(); 
Now that you have a variable of type Bitmap and a worksheet, you just need to insert the image on the sheet:
 System.Windows.Forms.Clipboard.SetDataObject(bitmap, false); xlsRange = xlSheet.get_Range((Excel.Range)xlSheet.Cells[5, 15], (Excel.Range)xlSheet.Cells[5, 15]); xlSheet.Paste(xlsRange, bitmap); 

So, the key is this guy here (instead of using AddPicture): Worksheet.Paste Method

Hope this helps!
+3
source

All Articles