In my MVC 5 Application I want to use Microsoft.Office.Interop.Excel library. I use Visual Studio 2013 and Office 2013. I added a reference Microsoft.Excel 15.0 Object Library and in my class I added using Excel = Microsoft.Office.Interop.Excel; When I click build it doesn’t shows any error and tells that Build Complete, but when I run my Application I’m getting this error
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1748: Cannot find the interop type that matches the embedded interop type 'Microsoft.Office.Interop.Excel.Application'. Are you missing an assembly reference?
Source Error:
[No relevant source lines]
Source File: Line: 0
What it could be?
asked Nov 25, 2013 at 16:46
![]()
3
You have assemblies for MS 2010 but you have installed office 2013. Assemblies are not forward compatible. You must install office the same version that your DLLs are or better use something like OpenXml sdk.
Then it looks that some necessary assembly is missing. You will have to add reference to assembly.
Cannot find the interop type that matches the embedded interop type ». Are you missing an assembly reference?
This method is similar to the previous error in that it occurs if one assembly embeds type information and another does not. In this case, you have an assembly, assembly1, that references a PIA assembly with Embed Interop Types is set to true. Assembly1 then exposes a type from the PIA assembly, for example as the return type from a method or property. Another assembly, assembly2, references assembly1 and makes use of the embedded type. The error occurs if assembly2 does not also reference the PIA assembly, and therefore cannot locate the embedded type information.
To resolve the issue, you need to add a reference from the second assembly to the PIA assembly and set the Embed Interop Types property to true. Thus, both assemblies will have a reference to the PIA assembly, with type information embedded, and both can utilize the embedded type.
http://blogs.msdn.com/b/vbteam/archive/2010/06/11/troubleshooting-errors-when-embedding-type-information-doug-rothaus.aspx
answered Nov 25, 2013 at 16:51
Jernej NovakJernej Novak
3,0861 gold badge38 silver badges43 bronze badges
2
This happens to me if I export an interop type. If the error is about Excel.Application then look for a public method or property on a public class that returns an Application reference or has an Application reference as a parameter (anything public that makes an interop type visible).
Either hide that class, property, or method by making it private or internal, or don’t return that type, or wrap the interop type in your own wrapper class and return that instead (which is better practice anyways.)
answered Aug 31, 2017 at 23:01
Dave CousineauDave Cousineau
11.7k8 gold badges65 silver badges77 bronze badges
Adding the reference dll file into the Bin folder will help to resolve this issue.
answered Jun 3, 2015 at 23:44
![]()
PraveenPraveen
1472 silver badges5 bronze badges
0
- Remove From My Forums
-
Question
-
Hi,
How to resolve
Error 1 The type or namespace name 'Excel' could not be found (are you missing a using directive or an assembly reference?) 59 13 WindowsFormsApplication2 Error 2 The name 'ExcelObj' does not exist in the current context 59 36 WindowsFormsApplication2 Error 3 The name 'openFileDialog1' does not exist in the current context 60 10 WindowsFormsApplication2 Error 4 The name 'Excel' does not exist in the current context 61 25 WindowsFormsApplication2
due to these?
Excel.WorkBook Book0 = ExcelObj.Workbooks.Open( openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "t", false, false, 0, true);
Many Thanks & Best Regards, Hua Min
Answers
-
Hi HuaMin,
You need to define these instances before using it. For example,
OpenFileDialog openFileDialog1 = new OpenFileDialog(); if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var ExcelObj = new Excel.Application(); Excel.Workbook Book0 = ExcelObj.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "t", false, false, 0, true); }We recommend that you could learn some basic concepts
about C#/.NET before coding.C# Programming Guide
Best Regards,
Li Wang
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.-
Marked as answer by
Monday, June 20, 2016 9:14 AM
-
Marked as answer by
Добрый день!
Собственно есть Win10, Visual Studio 2019, есть MS Office 2007 с установленным Excel.
При попытке подключиться к Excel вылезает ошибка «Could not load file or assembly «Interop.Microsoft.Office.Interop.Excel, Version=1.6.0.0, Culture=neutral, PublicKeyToken=null»» и прочее.
Ссылка на библиотеку добавлена (Microsoft Excel 12.0 Object Library версия 1.6). Цепляется из папки с офисом из файла Excel.exe.
В «C:Windowsassembly» Microsoft.Office.Interop.Excel присутствует.
Весь код
| C# | ||
|
DLL-ка Interop.Microsoft.Office.Interop.Excel.dll в папке Debug появляется после запуска. Наличие какого-либо осмысленного кода для работы с экселем ничего не дает, т.к. до него дело не доходит.
Единственное, что я заметил, это отличие версии в «C:Windowsassembly» (12.0.6600.1000) от той, которая отображается в проекте (12.0.6771.5000).
PS. Да, я находил темы про эту же ошибку, но не нашел в них решения.
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
- 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
-
Proposed as answer by
-
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.WorkbooksDim 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
-
Proposed as answer by
-
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
-
Proposed as answer by
Все привет, в этой статье опишу исчерпывающие примеры работы с excel на языке C#.
Для начала работы нам необходимо подключить библиотеку COM как на рисунке ниже:

Для этого добавляем ссылку в проект, надеюсь вы знаете как это делается) Выбираем пункт COM ищем библиотеку Microsoft Excel 16.0 Object Library ставим галочку и жмем Ок.
Далее нам не обходимо для сокращения записи и удобства создать алиас.

|
using Excel = Microsoft.Office.Interop.Excel; |
Теперь нам нужно объявить объект Excel задать параметры и приступать к работе.
|
//Объявляем приложение Excel.Application app = new Excel.Application { //Отобразить Excel Visible = true, //Количество листов в рабочей книге SheetsInNewWorkbook = 2 }; //Добавить рабочую книгу Excel.Workbook workBook = app.Workbooks.Add(Type.Missing); //Отключить отображение окон с сообщениями app.DisplayAlerts = false; //Получаем первый лист документа (счет начинается с 1) Excel.Worksheet sheet = (Excel.Worksheet)app.Worksheets.get_Item(1); //Название листа (вкладки снизу) sheet.Name = «Имя должно быть не больше 32сим»; |
Пример заполнения ячейки:
|
//Пример заполнения ячеек №1 for (int i = 1; i <= 9; i++) { for (int j = 1; j < 9; j++) sheet.Cells[i, j] = String.Format(«nookery {0} {1}», i, j); } //Пример №2 sheet.Range[«A1»].Value = «Пример №2»; //Пример №3 sheet.get_Range(«A2»).Value2 = «Пример №3»; |
Захват диапазона ячеек:
|
//Захватываем диапазон ячеек Вариант №1 Excel.Range r1 = sheet.Cells[1, 1]; Excel.Range r2 = sheet.Cells[9, 9]; Excel.Range range1 = sheet.get_Range(r1, r2); //Захватываем диапазон ячеек Вариант №2 Excel.Range range2 = sheet.get_Range(«A1»,«H9» ); |
Оформление, шрифт, размер, цвет, толщина.
|
//Шрифт для диапазона range.Cells.Font.Name = «Tahoma»; range2.Cells.Font.Name = «Times New Roman»; //Размер шрифта для диапазона range.Cells.Font.Size = 10; //Жирный текст range.Font.Bold = true; //Цвет текста range.Font.Color = ColorTranslator.ToOle(Color.Blue); |
Объединение ячеек в одну
|
//Объединение ячеек с F2 по K2 Excel.Range range3 = sheet.get_Range(«F2», «K2»); range3.Merge(Type.Missing); |
Изменяем размеры ячеек по ширине и высоте
|
//увеличиваем размер по ширине диапазон ячеек Excel.Range range2 = sheet.get_Range(«D1», «S1»); range2.EntireColumn.ColumnWidth = 10; //увеличиваем размер по высоте диапазон ячеек Excel.Range rowHeight = sheet.get_Range(«A4», «S4»); rowHeight.EntireRow.RowHeight = 50;range.EntireColumn.AutoFit();range.EntireColumn.AutoFit(); //авторазмер |
Создаем обводку диапазона ячеек
|
Excel.Range r1 = sheet.Cells[countRow, 2]; Excel.Range r2 = sheet.Cells[countRow, 19]; Excel.Range rangeColor = sheet.get_Range(r1, r2); rangeColor.Borders.Color = ColorTranslator.ToOle(Color.Black); |
Производим выравнивания содержимого диапазона ячеек.
|
Excel.Range r = sheet.get_Range(«A1», «S40»); //Оформления r.Font.Name = «Calibri»; r.Cells.Font.Size = 10; r.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; r.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; |
Примеры вычисления формул, все вставки формул были скопированы из самой Excel без изменений. Позиция ячейки взята из счетчика переменно и подставлен к букве ячейки
|
sheet.Cells[countRow, countColumn] = $«=G{countRow}-F{countRow}»; sheet.Cells[countRow, countColumn].FormulaLocal = $«=ЕСЛИ((H{countRow}*O{countRow})+(I{countRow}*P{countRow})/100<=0;J{countRow}*O{countRow}/100;((H{countRow}*O{countRow})+(I{countRow}*P{countRow}))/100)»; sheet.Cells[countRow, countColumn] = $«=K{countRow}+N{countRow}-R{countRow}»; sheet.Cells[33, 22].FormulaLocal = «=СУММ(V3:V32)»; |
Добавляем разрыв страницы.
|
//Ячейка, с которой будет разрыв Excel.Range razr = sheet.Cells[n, m] as Excel.Range; //Добавить горизонтальный разрыв (sheet — текущий лист) sheet.HPageBreaks.Add(razr); //VPageBreaks — Добавить вертикальный разрыв |
Как открыть фаил Excel
|
app.Workbooks.Open(@»C:UsersUserDocumentsExcel.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); |
Сохраняем документ Excel
|
app.Application.ActiveWorkbook.SaveAs(«MyFile.xlsx», Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); |
Завершение работы с объектом Excel.Application
|
app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); |
Пример как выбрать фаил и загрузив его и узнать количество заполненных строк и колонок в одном конкретном листе по имени.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
//поиск файла Excel OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect =false; ofd.DefaultExt = «*.xls;*.xlsx»; ofd.Filter = «Microsoft Excel (*.xls*)|*.xls*»; ofd.Title = «Выберите документ Excel»; if (ofd.ShowDialog() != DialogResult.OK) { MessageBox.Show(«Вы не выбрали файл для открытия», «Внимание», MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string xlFileName = ofd.FileName; //имя нашего Excel файла //рабоата с Excel Excel.Range Rng; Excel.Workbook xlWB; Excel.Worksheet xlSht; int iLastRow, iLastCol; Excel.Application xlApp = new Excel.Application(); //создаём приложение Excel xlWB = xlApp.Workbooks.Open(xlFileName); //открываем наш файл xlSht = xlWB.Worksheets[«Лист1»]; //или так xlSht = xlWB.ActiveSheet //активный лист iLastRow = xlSht.Cells[xlSht.Rows.Count, «A»].End[Excel.XlDirection.xlUp].Row; //последняя заполненная строка в столбце А iLastCol = xlSht.Cells[1, xlSht.Columns.Count].End[Excel.XlDirection.xlToLeft].Column; //последний заполненный столбец в 1-й строке |
Получаем список всех загруженных книг «листов» из файла
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//поиск файла Excel OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = false; ofd.DefaultExt = «*.xls;*.xlsx»; ofd.Filter = «Microsoft Excel (*.xls*)|*.xls*»; ofd.Title = «Выберите документ Excel»; if (ofd.ShowDialog() != DialogResult.OK) { MessageBox.Show(«Вы не выбрали файл для открытия», «Внимание», MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string xlFileName = ofd.FileName; //имя нашего Excel файла Excel.Workbook xlWB = ex.Workbooks.Open(xlFileName); ///загружаем список всех книг foreach (object item in xlWB.Sheets) { Excel.Worksheet sheet = (Excel.Worksheet)item; } |
- Remove From My Forums
-
Question
-
“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 interface with IID ‘{000208D5-0000-0000-c000-00000000046}’
failed due to the followinf error:Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).Not working in the follwing scenareo:
windows 10 64 bit os ,office 16 64 bit ,vb.net code compiled as 32, referenced the Microsoft.office.Interop.dll
from Gac and 15 version suitable for office 16.working in following scenareo :
windows 7 32 bit os , office 16 of 32 bit , vb.net code compiled as 32 bit.
tried solutions from google:
1)checked the registry key and fine it contains 1.9
2)repaired the office 16
3)compiled as ANY CPU ->excel working but app need to be run as 32 bit.
Is it problem with dll mapping , i didnt find separate dll for 32 bit or 64 bit microsoft.office.interop.dll
please suggest how to load proper dll so that export to excel should work on windows 10 , 64 bit os ,office 16 of 64 bit.code runs as 32 bit.
Answers
-
thanks for the reply .
In Specific to my case :
issue is resolved by deleting the existing configuration properties ->platform options (previously while creating soltion platforms x64 and anycpu ,settings are copied from x86 ).so even if i run as 64 or any cpu it behaves as 32 internally.so
all the target platform solution options were deleted and added freshly and for the setup ->changed the target from x86 to x64
1)right click on solution->configuration propertie->configuration manager->active solution platform->
x86 deletd
any cpu deleted
x64 deleted2)again created fresh x86,x64, any cpu and compiled with all options.
3)select appname.setup->view->properties window->Target platform->x64
now working fine as expected .
-
Proposed as answer by
Tuesday, May 22, 2018 8:55 AM
-
Marked as answer by
babji v
Tuesday, May 22, 2018 7:04 PM -
Edited by
babji v
Tuesday, May 22, 2018 7:04 PM
-
Proposed as answer by
- Remove From My Forums
-
Question
-
“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 interface with IID ‘{000208D5-0000-0000-c000-00000000046}’
failed due to the followinf error:Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).Not working in the follwing scenareo:
windows 10 64 bit os ,office 16 64 bit ,vb.net code compiled as 32, referenced the Microsoft.office.Interop.dll
from Gac and 15 version suitable for office 16.working in following scenareo :
windows 7 32 bit os , office 16 of 32 bit , vb.net code compiled as 32 bit.
tried solutions from google:
1)checked the registry key and fine it contains 1.9
2)repaired the office 16
3)compiled as ANY CPU ->excel working but app need to be run as 32 bit.
Is it problem with dll mapping , i didnt find separate dll for 32 bit or 64 bit microsoft.office.interop.dll
please suggest how to load proper dll so that export to excel should work on windows 10 , 64 bit os ,office 16 of 64 bit.code runs as 32 bit.
Answers
-
thanks for the reply .
In Specific to my case :
issue is resolved by deleting the existing configuration properties ->platform options (previously while creating soltion platforms x64 and anycpu ,settings are copied from x86 ).so even if i run as 64 or any cpu it behaves as 32 internally.so
all the target platform solution options were deleted and added freshly and for the setup ->changed the target from x86 to x64
1)right click on solution->configuration propertie->configuration manager->active solution platform->
x86 deletd
any cpu deleted
x64 deleted2)again created fresh x86,x64, any cpu and compiled with all options.
3)select appname.setup->view->properties window->Target platform->x64
now working fine as expected .
-
Proposed as answer by
Tuesday, May 22, 2018 8:55 AM
-
Marked as answer by
babji v
Tuesday, May 22, 2018 7:04 PM -
Edited by
babji v
Tuesday, May 22, 2018 7:04 PM
-
Proposed as answer by
Hello,
I am new to VB and have been trying to create a small app using excel. I went to the Microsoft support page and followed the instructions to add a reference to Excel 15.0 that is installed on my computer and then insert at the top of my Form1 the following «Imports Excel = Microsoft.Office.Interop.Excel» and the «Excel = Microsoft.Office.Interop.Excel» portion is underlined by the editor with no recommended solution. Do I need to upgrade my Visual Studio 2013 or install any add-ons? Any advice is greatly appreciated!
Here is the error I get when attempting to run the code
Warning 1 Namespace or type specified in the Imports 'Microsoft.Office.Interop.Excel' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. C:UsersPhilipDocumentsVisual Studio 2013ProjectsExcel projectsVBdotNetSetup 5-26-17VBdotNetSetup 5-26-17Form1.vb 4 9 VBdotNetSetup 5-26-17
What I have tried:
I have tried searching the Microsoft support pages and have had no luck.
Comments
1 solution
Solution 3
If you go to:
Visual Studio -> Main Menu -> Project -> Add Reference
Choose to see the COM objects, and if you have Microsoft Office installed, you should be able to scroll down to:
Microsoft Excel [xx.x] object library
After that, your IMPORTS declaration should work.
Comments
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


| Top Experts | |
| Last 24hrs | This month |
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900