Невозможно привести com объект типа microsoft office interop excel applicationclass

Reseller affiliate logo

Welcome ${RESELLERNAME} Customers

Please opt-in to receive reseller support

I agree that Autodesk may share my name and email address with ${RESELLERNAME} so that ${RESELLERNAME} may provide installation support and send me marketing communications.  I understand that the Reseller will be the party responsible for how this data will be used and managed.

Email Address

Email is required

Entered email is invalid.

I am attempting to capture some data from Excel from within a C# console application.

I get the error

Unable to cast COM object of type ‘microsoft.Office.Interop.Excel.ApplicationClass’ to ‘microsoft.Office.Interop.Excel.Application'»

This code used the ‘Microsoft Excel 12.0 Object Library’, and I included a reference to ‘Microsoft.Office.Interop.Excel’.

I dug a little bit this site and came across
Interop type cannot be embedded, but I could not understand it enough to implement what was suggested as a solution.

My .NET version is 4.5.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Excel = Microsoft.Office.Interop.Excel;

namespace deneme
{
class Program
{
    static void Main(string[] args)
    {

        Excel.Application xlApp = new Excel.Application();
        xlApp.Visible = true; // <-- excel application
        xlApp.DisplayAlerts = false;

        // Open the workbook.
        Excel.Workbook wBook = xlApp.Workbooks.Open("C:\FNN\XLA\fnnComTemplate.xlsx",
            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);

        // get the sheet
        Excel.Worksheet wSheet = wBook.Sheets[0];
        // foreach (Excel.Worksheet sheet in wBook.Sheets) { if (sheet.Name == "templateSheet") { wSheet = sheet; } }

        Excel.Range rng = wSheet.get_Range("A1");

        aux = wSheet.Range["F6"].Value;

        Console.WriteLine("interop result:" + aux);
        Console.ReadLine();

    }

}
}

  • Remove From My Forums
  • Question

  • I’m having trouble with Excel Interop.  I wrote a sample application:

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

    Dim xlApp As New Application()

    Dim objWorkbook As Workbook

    Dim objWorksheet As Worksheet

    Dim objRange As Range

    Dim intRow As Integer

    Dim intCell As Integer

    Dim strRow As New String(«»)

    ‘ Change the path to SOLVSAMP.XLS to match the path on your computer.

    objWorkbook = xlApp.Workbooks.Open _

    («C:Documents and Settingspmarino.USIDesktopsample.xls»)

    objWorksheet = objWorkbook.Worksheets.Item(1)

    objRange = objWorksheet.Range(«A2», «F16»)

    For intRow = 1 To 15

    For intCell = 1 To 6

    strRow = strRow & objRange.Cells(intRow, intCell).value & vbTab

    Next intCell

    Me.ListBox1.Items.Add(strRow)

    strRow = «»

    Next intRow

    End Sub

    This works fine while debugging.  When I publish the application to localhost and then run, I get this message: Unable to cast COM object of type ‘Microsoft.Office.Interop.Excel.ApplicationClass’ to interface type ‘Microsoft.Office.Interop.Excel._Application’. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{000208D5-0000-0000-C000-000000000046}’ failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)). on this line:

    Line 20:     objWorkbook = xlApp.Workbooks.Open _
    Line 21:         («C:Documents and Settingspmarino.USIDesktopsample.xls»)

    I have a reference to Microsoft.Office.Interop.Excel which is in c:Program FilesMicrosoft Visual Studio 9.0Visual Studio Tools for OfficePIAOffice11Microsoft.Office.Interop.Excel.dll

    Thanks for your help

Answers

  • I had this problem and it resolved after I ran the Office 2003 repair. Use Add Remove programs> Go to the tab Change or remove programs
    Go to Microsoft Office Professional 2003. Click the link «Click here for support information». Use Repair Button.

    This works.

    • Proposed as answer by

      Tuesday, March 2, 2010 2:08 AM

    • Marked as answer by
      Martin_XieModerator
      Friday, October 22, 2010 4:44 AM

  • Phil Marino,

    Based on your post, I created a new WindowsApplication1 in VB 2005 Express Edition. I copied a sample.xls, added reference of Excel Object Library 12.0 (I am using Office 2007) then use your code snippet with a Button and ListBox control. The application runs well when clicked debugging.

    I publish the application with the default location: http://localhost/WindowsApplication1/, then I can see the page that to install the project and run. The application runs well, too. I can see the result in the ListBox after clicking the button.

    I would like to suggest you to download the OleView.exe to see the related information on RegKeys, Typelib to track down the cause of your problem.

    Hope that can help you.

  • hi again…

    Im gonna answer myself hehe…

    I changed this in the code and now works in all the computer =)

    Dim oExcel As Excel.ApplicationClass —-> Dim oExcel As Excel.Application


    Dim oBooks As Excel.Workbooks

    Dim oBook As Excel.WorkbookClass ——> Dim oBook As Excel.Workbook

    D

    im oSheet As Excel.Worksheet

    • Proposed as answer by
      surendra singh samant
      Thursday, August 27, 2009 4:13 AM
    • Marked as answer by
      Martin_XieModerator
      Friday, October 22, 2010 4:43 AM

  • friends this is Balaji.

    i felt reliable to share the issue i solved. inface the one i face nd suffered from 2-3 days. this is for absolute beginners. Might the Big-B’s knw. but for a beginner newly coding involved with processes would find it help full.

    this error :-

    unable to cast com object of type ‘Microsoft.office.Interop.Excel.ApplicationClass’ to interface type ‘Microsoft.office.Interop.Excel._Application’ .

    The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

    if this arise — the one i solved is not exactly solution in all situations.  a case of mistake can be made by a beginner.

    the situation i solved :

    I tried to kill all the EXCEL processes as some times i used to get the excel file is being used by another processes.

    Solution :

    by doing that we are killing almost the connectivity to the excel. because we import excel in vb.net that process — even that process gets killed nd so the interop classes functionality stops working as the classes connectivity to excel is broken.

    that means by any means if the excel process is terminated we wil get that error.

    • Proposed as answer by
      balajivalla
      Tuesday, September 7, 2010 7:33 AM
    • Marked as answer by
      Martin_XieModerator
      Friday, October 22, 2010 4:44 AM

На одном компьютере (WinXP MSOffice 2007) при попытке выгрузить отчет из самописной (.NET 3.5) программы в Excel проявилась следующая ошибка: Невозможно привести COM-объект типа «Microsoft.Office.Interop.Excel.ApplicationClass» к интерфейсному типу «Microsoft.Office.Interop.Excel._Application». Операция завершилась со сбоем, поскольку вызов QueryInterface COM-объекта для интерфейса с IID «{000208D5-0000-0000-C000-000000000046}» возвратил следующую ошибку: Ошибка при загрузке библиотеки. (Исключение из HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).

Ну да, программа компилировалась на компе с MSOffice 2003, и это наложило определенный отпечаток на набор ее библиотек. Но ведь на других станциях всё работает… Единственная особенность — на проблемной машине зачем-то были установлены primary interop assemblies 2007. В итоге помог метод грубой силы: деинсталляция этих самых assemblies и восстановление офиса.

UPD 2018-08-10: По крайней мере, в одном случае удалось установить причину этой ошибки. Как оказалось, по адресу HKEY_CLASSES_ROOTInterface{000208D5-0000-0000-C000-000000000046}TypeLib лежит некий guid (в моём случае {00020813-0000-0000-C000-000000000046}) и номер версии, который нужно использовать (в моём случае 1.6).

Так вот, в ветке реестра HKCRTypeLib{00020813-0000-0000-C000-000000000046} перечислены разные версии, и среди них оказалась одна запись (1.9), оставшаяся от деинсталлированного офиса 2010. Если эту запись, отсылающую к несуществующей версии excel-а, удалить, то ошибка пропадает.

Навело на решение это обсуждение.

Это моя первая попытка захватить некоторые данные из excel из одного консольного приложения С#.

Я получаю сообщение об ошибке «неспособный передать объект COM типа» microsoft.Office.Interop.Excel.ApplicationClass «в» microsoft.Office.Interop.Excel.Application «.

Этот код использовал «библиотеку объектов Microsoft Excel 12.0», и я дал ссылку на Microsoft.Office.Interop.Excel.

Тем не менее, я не мог преодолеть эту ошибку, которая, как я считаю, имеет свое быстрое решение.

Я немного выкопал этот сайт и наткнулся на это решение: тип Interop не может быть встроен

Однако я не мог понять, поэтому не мог реализовать то, что было предложено в качестве решения.

Моя.Net версия 4.5.

Любая помощь очень ценится.

Заранее спасибо.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Excel = Microsoft.Office.Interop.Excel;

namespace deneme
{
class Program
{
    static void Main(string[] args)
    {

        Excel.Application xlApp = new Excel.Application();
        xlApp.Visible = true; // <-- excel application
        xlApp.DisplayAlerts = false;

        // Open the workbook.
        Excel.Workbook wBook = xlApp.Workbooks.Open("C:\FNN\XLA\fnnComTemplate.xlsx",
            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);

        // get the sheet
        Excel.Worksheet wSheet = wBook.Sheets[0];
        // foreach (Excel.Worksheet sheet in wBook.Sheets) { if (sheet.Name == "templateSheet") { wSheet = sheet; } }

        Excel.Range rng = wSheet.get_Range("A1");

        aux = wSheet.Range["F6"].Value;

        Console.WriteLine("interop result:" + aux);
        Console.ReadLine();

    }

}
}

Понравилась статья? Поделить с друзьями:
  • Невозможно привести com объект типа excel applicationclass к интерфейсному типу excel application
  • Невозможно получить доступ к excel файлу
  • Невозможно подключиться к microsoft excel driver 1с
  • Невозможно переместить ячейки в таблице или диапазоне с примененным фильтром excel
  • Невозможно передать данные в excel