Is is possible to insert an image into an excel ce

2019-01-26 01:45发布

问题:

I have used automation to insert values into a cell, however I have never seen any documentation, for example, that demonstrate inserting anything other than text and/or formula's.

Has anybody been able to insert an image from an external application?

回答1:

Dim FileName as string
FileName="c:\text.jpg"
Set NewPic = ActiveSheet.Pictures.Insert(FileName)
NewPic.top=100
NewPic.left=100

If you want to position the picture to a specific cell then select that cell as a range and use that ranges top/left/with to position the picture.

Samples: http://exceltip.com/st/Insert_pictures_using_VBA_in_Microsoft_Excel/486.html

Note: In Excel cells cannot contain pictures. The pictures live on an invisible drawing layer that floats about the cells. They can be positioned based on the cell coordinates, which makes it feel like they are living "in" the cells.



回答2:

I see it's already been answered, but see my post here.

Basically rather than use the Worksheet.Pictures.Insert method (which the MSDN recommends you don't use directly, and which returns a raw COM object), try the Worksheet.Shapes.AddPicture method instead.

Dim range As Microsoft.Office.Interop.Excel.Range
Dim pic as Microsoft.Office.Interop.Excel.Shape
Dim filePath as String

range = ...
filePath = ...
pic = range.Worksheet.Shapes.AddPicture(filePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, range.Left, range.Top, 300, 300)

It's not quite as straightforward because you have to specify the exact position and dimensions, but otherwise, pretty cool!



回答3:

Sure, the following code gives a good example using the Microsoft Interop libraries:

   string excelfilename = @"C:\excelfile.xlsx";
   string picturename = @"C:\image.jpg";

    object missing = Type.Missing;
    Microsoft.Office.Interop.Excel.Application app = new ApplicationClass();
    Workbook book =  app.Workbooks.Add(missing);
    Worksheet sheet = (Worksheet)book.ActiveSheet;
    Pictures pics = (Pictures)sheet.Pictures(missing);
    pics.Insert(picturename, missing);
    book.SaveAs(excelfilename, missing, missing, missing, missing, missing, XlSaveAsAccessMode.xlNoChange,
        missing, missing, missing, missing, missing);
    app.Quit();
    app = null;