Using excel microsoft office interop excel ошибка

aldookar

0 / 0 / 0

Регистрация: 10.02.2013

Сообщений: 60

1

11.02.2013, 00:22. Показов 37295. Ответов 10

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет! Кто может подсказать мне как заставить работать это у строчку:

C#
1
using Excel = Microsoft.Office.Interop.Excel;

Ошибка «Имя типа или пространства имен «Office» отсутствует в пространстве имен «Microsoft»».
Везде в интернете пишут что нужно добавить в Reference Microsoft.Office, но у меня студия на русском и я не могу понять куда это добавлять.



0



28 / 28 / 6

Регистрация: 25.12.2008

Сообщений: 186

11.02.2013, 01:47

2

Цитата
Сообщение от aldookar
Посмотреть сообщение

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

В ссылки…



0



460 / 441 / 75

Регистрация: 26.12.2012

Сообщений: 2,883

11.02.2013, 10:27

3

вот на скрине видно в англоязычной версии вместо слова ссылка у вас будет написано references
p.s ставьте лучше англоязычную версию

Миниатюры

Имя типа или пространства имен "Office" отсутствует в пространстве имен "Microsoft"
 



1



0 / 0 / 0

Регистрация: 10.02.2013

Сообщений: 60

11.02.2013, 13:25

 [ТС]

4

Блин значит у меня чего то нет…

Имя типа или пространства имен "Office" отсутствует в пространстве имен "Microsoft"



0



460 / 441 / 75

Регистрация: 26.12.2012

Сообщений: 2,883

11.02.2013, 13:51

5

на вкладке COM ищите

Миниатюры

Имя типа или пространства имен "Office" отсутствует в пространстве имен "Microsoft"
 



3



56 / 56 / 14

Регистрация: 06.04.2012

Сообщений: 185

11.02.2013, 13:54

6

Вкладка «Обзор», и далее — C:WindowsAssembliesGACMicrosoft.Office.Interop.Excel и выберите нужную версию, это если у вас семерка, если ХР, то вроде бы понадобится установить PIA для вашей версии офиса(2003,2007), качается оно с сайта майкрософта (например для 2003 офиса — http://www.microsoft.com/en-us… x?id=20923), хотя, так как вам не просто использовать, а разрабатывать, то возможно еще понадобится(в случае ХР) установить VSTO



2



0 / 0 / 0

Регистрация: 10.02.2013

Сообщений: 60

11.02.2013, 14:12

 [ТС]

7

Спасибо! Дальше уже сам думаю разберусь.



0



0 / 0 / 0

Регистрация: 10.02.2013

Сообщений: 60

12.02.2013, 17:58

 [ТС]

8

Решил не создавать новую тему и написал здесь.
Как считывать с exel файла и попутно обрабатывать?
т.е. первый столбец это текст, второй это один из вариантов combobox, третий проверка на истину или лож и т.д.

Добавлено через 1 час 32 минуты
Нашел! Кому интересно вот ссылка



0



aldookar

0 / 0 / 0

Регистрация: 10.02.2013

Сообщений: 60

17.02.2013, 17:02

 [ТС]

9

Всем привет! Снова зашел в тупик…

C#
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
26
27
28
29
{
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //Создаём приложение.
                Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
                //Открываем книгу.                                                                                                                                                        
                Microsoft.Office.Interop.Excel.Workbook ObjWorkBook = ObjExcel.Workbooks.Open(openFileDialog1.FileName, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
                //Выбираем таблицу(лист).
                Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
                ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[1];
 
                //Выбираем первые сто записей из столбца.
                for (int i = 0; i < 101; i++)
                {
                    //Выбираем область таблицы.
                    Microsoft.Office.Interop.Excel.Range range = ObjWorkSheet.get_Range("A" + (i+8).ToString(), "A" + (i+8).ToString());
 
                    MessageBox.Show(range.Text.ToString());
                    //Добавляем полученный из ячейки текст.
                    dataGridViewDan.Rows[i].Cells[0].Value = range.Text.ToString();
          
                    Application.DoEvents();
                }
 
                //Удаляем приложение
                ObjExcel.Quit();
            }
 
        }

Код записывает первую строчку в сетке, но не создает вторую…

Добавлено через 2 часа 3 минуты
И с этим разобрался. Добавил в цикл dataGridViewDan.Rows.Add(); и все работает!

Добавлено через 1 минуту
Блин он пустые строчки создает…

Добавлено через 30 минут
Поставил dataGridViewDan.Rows.Add(); перед dataGridViewDan.Rows[i].Cells[0].Value = range.Text.ToString(); и работает почти правильно… Вот только лишняя строчка снизу…



0



Сосна15

13 / 12 / 1

Регистрация: 02.10.2017

Сообщений: 22

02.10.2017, 16:27

10

Цитата
Сообщение от aldookar
Посмотреть сообщение

Всем привет! Кто может подсказать мне как заставить работать это у строчку:

C#
1
using Excel = Microsoft.Office.Interop.Excel;

Ошибка «Имя типа или пространства имен «Office» отсутствует в пространстве имен «Microsoft»».
Везде в интернете пишут что нужно добавить в Reference Microsoft.Office, но у меня студия на русском и я не могу понять куда это добавлять.

Столкнулся с той же проблемой. В русской ВидеоСтудии трудно понять куда заходить, чтобы установить компонент Экселя.

Решение такое:

В Обозревателе решений жмём правой кнопкой на свой проект, появляется окошко контекстного меню.
Выбираем Добавить ссылку... -> Открывается искомое окно (с надписью на английском): Add reference
Далее выбираем вкладку .NET, а в ней наш долгожданный Microsoft.Office.Interpop.Excel



1



SeIZVeIZ

02.10.2017, 16:52


    Имя типа или пространства имен «Office» отсутствует в пространстве имен «Microsoft»

Не по теме:

Сосна15, на дату смотреть не учили?



0



  • Remove From My Forums
  • Question

  • I am trying to use this namespace and downloaded the O2003pia.exe from http://support.microsoft.com/kb/897646.

    I ran the msi and see the Interop files in the GAC but when I try to ‘Add a Reference’ in VS2005, I do not see any of the Interop namespaces.

    I already had Office 2003 installed before I ran the above msi.

    What else am I doing wrong. Why aren’t these included with VS2005 in the first place…………..

    Please help,

    JJM

Answers

  • Hi JJJMonty,

    Actually, if you want to use this DLL, following these steps:

    1.       On the Project menu, click Add Reference.

    2.       On the COM tab, locate Microsoft Excel Object Library, and then click Select. In Visual Studio 2005, locate Microsoft Excel 11.0 Object Library on the COM tab.

    3.       Click OK in the Add References dialog box to accept your selections. If you are prompted to generate wrappers for the libraries that you selected, click “Yes”.

    Then you should be able to use this interop DLL, for more details, please visit Primary Interop Assemblies.

    Hope this helps!

    Thanks!

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?

Daniel A. White's user avatar

asked Nov 25, 2013 at 16:46

Bryuk's user avatar

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 Novak's user avatar

Jernej NovakJernej Novak

3,1551 gold badge33 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 Cousineau's user avatar

Dave CousineauDave Cousineau

11.9k8 gold badges61 silver badges78 bronze badges

Adding the reference dll file into the Bin folder will help to resolve this issue.

answered Jun 3, 2015 at 23:44

Praveen's user avatar

PraveenPraveen

1472 silver badges5 bronze badges

0

  • 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

Это код, который я использовал до установки Office 2016.

var excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(finfo.FullName, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "t", false, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
var cellValue =(excelWorksheet.Cells[a, b] as Excel.Range).Value;

Код работал нормально, но после установки Office 2016 я увидел, что не могу использовать using Excel = Microsoft.Office.Interop.Excel;

Единственная совместимая библиотека, которую я нашел,

Microsoft.Office.Core (библиотека объектов Microsoft Office 16.0)

Я не смог найти примеров доступа к файлам Excel. Есть ли другой способ доступа к файлам Excel с установленным Office 2016 (PIA)

Это ошибка, которую я получаю, когда пытаюсь запустить код

Невозможно привести объект COM типа «System.__ComObject» к типу интерфейса «Microsoft.Office.Interop.Excel.Application». Эта операция завершилась неудачно, поскольку вызов QueryInterface в компоненте COM для интерфейса с IID ‘{000208D5-0000-0000-C000-000000000046}’ не выполнен из-за следующей ошибки: Интерфейс не зарегистрирован (Исключение из HRESULT: 0x80040155).

Понравилась статья? Поделить с друзьями:
  • Users usr общая файловая ошибка при доступе
  • Usergate ошибка соединения сервер недоступен 0
  • Usergate ошибка подключения к серверу
  • Usergate 10061 ошибка соединения с сервером
  • Userassembly dll genshin impact ошибка