Is is possible to insert an image into an excel cell via COM?

前端 未结 3 429
有刺的猬
有刺的猬 2020-12-18 15:49

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 for

相关标签:
3条回答
  • 2020-12-18 16:28
    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.

    0 讨论(0)
  • 2020-12-18 16:36

    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!

    0 讨论(0)
  • 2020-12-18 16:38

    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;
    
    0 讨论(0)
提交回复
热议问题