Adding an image from memory stream to Excel document
I have an image in a memory stream and I want to write this to an MS Excel document, the PIA only exposes the AddPicture method which takes a file path.
Is there away to add a picture without having to write the image to disc?
MSDN
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.shapes.addpicture(v=office.14).aspx
Well, a bit of blind flying but assuming a thing or two about your code (eg the source of your stream, data type, etc) this could be a solution:
First, you need to create bitmap image data from the stream (which I assume is a byte stream, also assuming that the stream describes a bitmap image). There's a solution already for that here on Stack Overflow: Byte Array to Bitmap Image
I copy-paste 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 assuming you have an object for your workbook and the worksheet you are about to work with, something like this: xlBook = (Excel.Workbook)objExcel.Workbooks.Add("");
xlSheet = (Excel.Worksheet)xlBook.Worksheets1;
xlSheet.Activate();
Now that you have a Bitmap-type variable, and a worksheet, all you need is to paste the image to 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! 链接地址: http://www.djcxy.com/p/13156.html
上一篇: 输入不应该使用的名称?
下一篇: 将内存流中的图像添加到Excel文档中