Cannot insert object AddOLEObject Excel C#

Sunny Dhiman 1 Reputation point
2021-01-15T09:14:13.85+00:00

Cannot insert object.
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Shapes.AddOLEObject(Object ClassType, Object Filename, Object Link, Object DisplayAsIcon, Object IconFileName, Object IconIndex, Object IconLabel, Object Left, Object Top, Object Width, Object Height)
at WordSample.Form1.button1_Click(Object sender, EventArgs e) in C:\Test Projects\WordSample\WordSample\Form1.cs:line 30

Code:

  private void button1_Click(object sender, EventArgs e)  
    {  
        try  
        {  
            Excel.Application app = new Excel.Application();  
            Excel.Workbook wb = null;  
            wb = app.Workbooks.Open(@"C:\Temp_Statoil\mal_malingsprogram.xls",  
                                        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,  
                                        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  
            InsertStaticIndexSheetsPreWpkTemplate(wb);  
            Excel._Worksheet wsMal = (Excel._Worksheet)wb.Sheets[pageTemplate];  
            Excel._Worksheet wsTotalOverView = (Excel._Worksheet)wb.Sheets[pageTotal];  
            //foreach (Excel.Worksheet ws in wb.Worksheets)  
            //    sheetNames.Add(ws.Name);  
            wsMal.Copy(wsMal, Type.Missing);  
            Excel._Worksheet wsCurrent = (Excel._Worksheet)wb.Sheets[(wsMal.Index - 1)];  
            Excel.Range unitIcon = wsCurrent.get_Range("K11", Type.Missing);  
  
            Excel.Shape shape = wsCurrent.Shapes.AddOLEObject(  
                   Type.Missing,  
                   @"C:\Temp_Statoil\tmpFiles\1C9.pdf",  
                   false,  
                   true,  
                    @"C:\Temp_Statoil\pdf.ico",  
                   0,  
                   "Doubleclick to open drawing for 1C9",  
                  unitIcon.Left,  
                    unitIcon.Top,  
                   Type.Missing,  
                   Type.Missing);  
  
            shape.Locked = false;  
            shape.Name = "Unit drawing [1C9]";  
            Marshal.ReleaseComObject(shape);  
            ((Excel._Worksheet)wb.Sheets[1]).Activate();  
            wb.SaveAs(  
                Filename: @"C:\temp\test"+DateTime.Now,  
                FileFormat: Excel.XlFileFormat.xlOpenXMLWorkbook,  
                Password: Type.Missing,  
                WriteResPassword: Type.Missing,  
                ReadOnlyRecommended: Type.Missing,  
                CreateBackup: Type.Missing,  
                AccessMode: Excel.XlSaveAsAccessMode.xlNoChange,  
                ConflictResolution: Type.Missing,  
                TextCodepage: Type.Missing,  
                Local: Type.Missing);  
  
            wb.Close();  
        }  
        catch (Exception ex)  
        {  
            MessageBox.Show(ex.Message);  
        }  
    }  
  
    protected void InsertStaticIndexSheetsPreWpkTemplate(Excel.Workbook wb)  
    {  
        //Insert static sheets in "Innhold-arket" (english: Index sheet).  
        foreach (Excel.Worksheet ws in wb.Sheets)  
            if (ws.Name.ToLower() != pageTemplate.ToLower())  
                InsertIndex(wb, ws.Name, "", "", "", ws.Name);  
            else  
                break;  
    }  
  
    public void InsertIndex(Excel.Workbook wb, string sheetName, string lv1, string lv2, string lv3, string linkDescription)  
    {  
        Excel.Worksheet indexSheet = (Excel.Worksheet)wb.Sheets[pageContents];  
        indexSheet.get_Range(string.Format("A{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = nextIndexNo;  
        indexSheet.get_Range(string.Format("B{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = lv1;  
        indexSheet.get_Range(string.Format("C{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = lv2;  
        indexSheet.get_Range(string.Format("D{0}", nextIndexNo + firstIndexLine), Type.Missing).Value = lv3;  
  
        Excel.Range linkRange = indexSheet.get_Range(string.Format("E{0}", nextIndexNo + firstIndexLine), Type.Missing);  
        linkRange.Hyperlinks.Add(linkRange, "", string.Format("'{0}'!A1", sheetName), Type.Missing, linkDescription);  
        nextIndexNo++;  
    }  

Directory structure:

56910-directory.png

57084-directory1.png

{count} votes

2 answers

Sort by: Most helpful
  1. Erin Ding-MSFT 4,461 Reputation points
    2021-01-18T05:11:34.19+00:00

    @Sunny Dhiman

    Tag “office-excel-itpro” focuses on general issues about Excel clients.
    Based on your description, your issue is more related to code.
    I would modify the tag to be “office-vba-dev”.
    Thanks for your understanding.


    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. David 151 Reputation points
    2021-07-09T08:07:09.513+00:00

    Try this solution. You'll need to install Spire.XLS through NuGet before you're able to compile the following code sample.

    using Spire.Xls;
    using Spire.Xls.Core;
    using System.Drawing;
    using Spire.Pdf;
    
    namespace InsertPdfAsOleObject
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                string excelPath = @"C:\Users\Administrator\Desktop\source.xlsx";
                string pdfPath = @"C:\Users\Administrator\Desktop\data.pdf";
    
                //Load Excel file
                Workbook workbook = new Workbook();
                workbook.LoadFromFile(excelPath);
    
                //Get the first worksheet
                Worksheet sheet = workbook.Worksheets[0];
    
                //Create an image from the first page of pdf
                Image image = GetImage(pdfPath);
    
                //Embed pdf as OLE object in the sheet
                IOleObject oleObject = sheet.OleObjects.Add(pdfPath, image, OleLinkType.Embed);
                oleObject.ObjectType = OleObjectType.AdobeAcrobatDocument;
                oleObject.Location = sheet.Range["B4"];
    
                //Save to file
                workbook.SaveToFile("result.xlsx", ExcelVersion.Version2016);
    
            }
    
            //Create an image from pdf
            public static Image GetImage(string pdfPath)
            {
                PdfDocument pdf = new PdfDocument(pdfPath);
                return pdf.SaveAsImage(0);
            }
        }
    }
    
    0 comments No comments