将内存stream中的图像添加到Excel文档

我有一个内存stream中的图像,我想写这个MS Excel文件,PIA只公开AddPicture方法,它需要一个文件path。

有没有添加图片,而不必将图像写入光盘?

MSDN

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

那么,有一点盲目飞行,但假设一两件关于你的代码(例如你的stream的来源,数据types等),这可能是一个解决scheme:
首先,您需要从stream中创build位图图像数据(我假设它是一个字节stream,并假定该stream描述了一个位图图像)。 已经有一个解决scheme已经在这里堆栈溢出: 字节数组到位图图像
我从解决scheme中复制粘贴代码:

int w= 100; int h = 200; int ch = 3; //number of channels (ie. assuming 24 bit RGB in this case) 
byte[] imageData = new byte[w h ch]; //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,w h ch); bitmap.UnlockBits(bmData);

另外假设你有一个工作簿和工作表的对象,你将要使用的东西是这样的:

 xlBook = (Excel.Workbook)objExcel.Workbooks.Add(""); xlSheet = (Excel.Worksheet)xlBook.Worksheets 1 ; xlSheet.Activate(); 

现在您已经有了一个Bitmaptypes的variables和一个工作表,您只需将图像粘贴到工作表:

 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); 

所以关键是这个人在这里(而不是使用“AddPicture”): Worksheet.Paste方法

希望这可以帮助!