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

aldookar

0 / 0 / 0

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

Сообщений: 60

1

11.02.2013, 00:22. Показов 37195. Ответов 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,1451 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

Это код, который я использовал до установки 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).

Do the following steps, which should be helpful in finding, adding, and using the Microsoft.Office.Interop.Excel.dll reference.

  • Start Visual Studio.
  • On the File menu, point to New, and then click Project. The New Project dialog box appears.
  • In the Installed Templates pane, expand Visual C#, and then click Windows.
  • Look at the top of the New Project dialog box to make sure that .NET Framework 4 (or later version) is selected as a target framework.
  • In the Templates pane, click Console Application.
  • Type a name for your project in the Name field.
  • Click OK.

The new project appears in Solution Explorer.

To add Microsoft.Office.Interop.Excel.dll references

  • In Solution Explorer, right-click your project’s name and then click Add Reference. The Add Reference dialog box appears.
  • On the Assemblies page, select Microsoft.Office.Interop.Word (optional) in the Component Name list, and then hold down the CTRL key and select Microsoft.Office.Interop.Excel. If you do not see the assemblies, you may need to ensure they are installed and displayed.
  • Click OK.

To Add the Reference, use the following directives:

  • In Solution Explorer, right-click the Program.cs file and then click View Code.
  • Add the following using directives to the top of the code file:
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;

Понравилась статья? Поделить с друзьями:
  • Users usr общая файловая ошибка при доступе
  • Userinit exe ошибка приложения
  • Usergate ошибка соединения сервер недоступен 0
  • Usergate ошибка подключения к серверу
  • Usergate ошибка 10049