Microsoft office 2007 primary interop assemblies что это
I installed Office 2013 and VS2013 on Windows 8.1 - when I now open old Projects which reference the version 12 PIAs (for Office 2007) these are missing in the references since VS2013 does only install Version 14 and 15 of the PIAs.
Since I want to Keep using PIA 12 I do not want to change the references. Instead I'd like to Register the Version 12 PIA's with VS2013. How can I achieve this?
I already tried using the PIA redistributable, but it does not want to work unless I install Office 2007, too (which I don't want). I can get a copy of the dlls from some other system, but how do I register These with Visual Studio 2013 (I don't need them in the GAC, I think, just in VS2013).
As far as I know for the PIA some COM class ID's should be recorded, I just don't know how/which.
Edit:
Right now the PIA dlls are referenced just by Name and Fingerprint/public key (no hint path). When I open the reference Panel in VS2013 they will Show up, can be selected and work. They seem to be registered somewhere so VS2013 can find them. I just want to replicate this on other Computers.
You are not thinking ahead. You don't stand a chance to diagnose and fix a bug in your code when your client uses Office 2007 unless you have that version installed as well. Either change your prerequisites and demand the user updates his Office version or install the Office version you need to provide support.
This is just one computer of the several who share this source. And I neither need nor want Office 2007 on every computer, since I'll have to debug other versions, too.
The funny thing is: When I install VS2008 these old PIAs will be registered in VS2013 even without having Office 2007 installed. But I don't want to install a full fledged old VS I don't need just for the PIAs. There must be a way to register them without having to install lots of other stuff.
Roger, as I wrote right above your comment, one of my other development Computers has the Office 2007 PIAs installed and registered but had never Office 2007 installed, so that answer obviously not complete (since some older VS can install them, there sure must be a way to do this, I'm just missing the 'how').
1 Answer 1
I've got the exact same setup, a machine with Windows 8.1 and only Office 2013 installed. No trouble at all getting the Office 2007 PIAs installed. Do beware that this is a two-step process. After you downloaded PrimaryInteropAssembly.exe from the Microsoft server and started it, you prompts you to give a directory to store intermediate files. Navigate to that directory, right-click the o2007pia.msi file and select Install to get them actually registered.
It isn't the only way to get them onto your machine. If you have another machine with the PIAs installed then create a dummy project and add the references to the Microsoft.Interop assemblies you need. Select them and ensure that the "Embed Interop Types" property is set to False and the "Copy Local" property is set to True. Build the project, you'll get the interop assemblies in the bin\Debug directory. Copy them to your machine and use the Browse button to add a reference to them. You always want the "Embed Interop Types" property set to True in your real project so you don't have to deploy the PIA on your user's machine anymore. Check them in with your project so you don't lose them again.
Для использования компонентов приложения Microsoft Office из проекта Office необходимо использовать основную сборку взаимодействия (PIA) для приложения. Основная сборка взаимодействия позволяет управляемому коду взаимодействовать с основанной на COM объектной моделью приложения Microsoft Office.
Интересуетесь разработкой решений, расширяющих возможности Office на нескольких платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office имеют небольшой объем по сравнению с надстройками и решениями VSTO, и их можно создавать с помощью практически любой технологии веб-программирования, такой как HTML5, JavaScript, CSS3 и XML.
При создании нового проекта Office Visual Studio добавляет ссылки на основные сборки взаимодействия, которые нужны для сборки проекта. в некоторых сценариях может потребоваться добавить ссылки на другие сборки pia (например, можно использовать функцию Microsoft Office Word в проекте для Microsoft Office Excel).
в этой статье описываются следующие аспекты использования Microsoft Office pia в проектах Office.
Дополнительные сведения о первичных сборках взаимодействия см. в разделе основные сборки взаимодействия.
Разделяйте основные сборки взаимодействия для сборки и запуска проектов
Visual Studio использует разные наборы основных сборок взаимодействия на компьютере разработки. Эти разные наборы сборок хранятся в следующих расположениях.
Папка в каталоге Program Files
Этот набор сборок используется при написании кода и построении проектов. Visual Studio устанавливает эти сборки автоматически.
Глобальный кэш сборок
Этот набор сборок используется в некоторых задачах разработки, например при запуске или отладке проектов. Visual Studio не устанавливает и не регистрирует эти сборки. необходимо сделать это самостоятельно.
Основные сборки взаимодействия в каталоге Program Files
Сборки PIA автоматически добавляются в расположение в файловой системе вне глобального кэша сборок при установке Visual Studio. При создании нового проекта Visual Studio автоматически добавляет ссылки на эти копии основных сборок взаимодействия в ваш проект. Visual Studio использует эти копии основных сборок взаимодействия вместо сборок в глобальном кэше для разрешения ссылок при разработке и построении проекта.
для Visual Studio 2017 и более поздних версий эти копии основных сборок взаимодействия устанавливаются в следующие общие расположения на компьютере разработчика:
%ProgramFiles%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\
(или %ProgramFiles(x86)%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\ в 64-разрядных операционных системах)
для более старых версий Visual Studio эти сборки pia будут установлены в папку набор средств Visual Studio для Office \пиа в %ProgramFiles% папке для этой версии Visual Studio. Пример: %ProgramFiles(x86)%\Microsoft Visual Studio 14.0\Visual Studio Tools for Office\PIA\
Основные сборки взаимодействия в глобальном кэше сборок
Office pia не требуются для запуска Office решений на компьютерах конечных пользователей. дополнительные сведения см. в разделе разработка и создание Office решений.
использование функций нескольких Microsoft Office приложений в одном проекте
Каждый шаблон проекта Office в Visual Studio предназначен для работы с одним приложением Microsoft Office. чтобы использовать функции в нескольких Microsoft Office приложениях или использовать функции в приложении или компоненте, у которых нет проекта в Visual Studio, необходимо добавить ссылку на необходимые pia.
в большинстве случаев следует добавить ссылки на основные сборки взаимодействия, установленные Visual Studio в %ProgramFiles(x86)%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\ каталоге. Эти версии сборок отображаются на вкладке платформа диалогового окна Диспетчер ссылок . дополнительные сведения см. в разделе инструкции. назначение Office приложений с помощью основных сборок взаимодействия.
Некоторые сборки добавляются в проект автоматически при добавлении сборки, которая на них ссылается. например, ссылки на Office.dll Microsoft.Vbe.Interop.dll сборки и добавляются автоматически при добавлении ссылки на слово, Excel, Outlook, Microsoft forms или сборки Graph.
основные сборки взаимодействия для приложений Microsoft Office
В следующей таблице перечислены основные сборки взаимодействия, доступные для Office 2016 , Office 2013 и Office 2010 .
To use the features of a Microsoft Office application from an Office project, you must use the primary interop assembly (PIA) for the application. The PIA enables managed code to interact with a Microsoft Office application's COM-based object model.
Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.
When you create a new Office project, Visual Studio adds references to the PIAs that are required to build the project. In some scenarios, you might need to add references to other PIAs (for example, you can use a feature of Microsoft Office Word in a project for Microsoft Office Excel).
This article describes the following aspects of using the Microsoft Office PIAs in Office projects:
For more information about primary interop assemblies, see Primary interop assemblies.
Separate primary interop assemblies to build and run projects
Visual Studio uses different sets of the PIAs on the development computer. These different sets of assemblies are in the following locations:
A folder in the program files directory
This set of the assemblies is used when you write code and build projects. Visual Studio installs these assemblies automatically.
The global assembly cache
This set of the assemblies is used during some development tasks, such as when you run or debug projects. Visual Studio doesn't install and register these assemblies; you need to do it yourself.
Primary interop assemblies in the program files directory
The PIAs are automatically added to a location in the file system, outside of the global assembly cache, while you install Visual Studio. When you create a new project, Visual Studio automatically adds references to these copies of the PIAs to your project. Visual Studio uses these copies of the PIAs, instead of the assemblies in the global assembly cache, to resolve type references when you develop and build your project.
When different versions of the PIAs are registered in the global assembly cache, you can face several development issues. The added copies of PIAs will help you to avoid such issues.
For Visual Studio 2017 and later, these copies of the PIAs are installed to following shared locations on the development computer:
%ProgramFiles%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\
(or %ProgramFiles(x86)%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\ on 64-bit operating systems)
For older versions of Visual Studio, these PIAs will be installed to the Visual Studio Tools for Office\PIA folder under the %ProgramFiles% folder for that version of Visual Studio. For Example: %ProgramFiles(x86)%\Microsoft Visual Studio 14.0\Visual Studio Tools for Office\PIA\
Primary interop assemblies in the global assembly cache
To perform certain development tasks, the PIAs must be installed and registered in the global assembly cache on the development computer. Typically, the PIAs are installed automatically when you install Office on the development computer. For more information, see Configure a computer to develop Office solutions.
The Office PIAs aren't required on end-user computers to run Office solutions. For more information, see Design and create Office solutions.
Use features of multiple Microsoft Office applications in a single project
Every Office project template in Visual Studio is designed to work with a single Microsoft Office application. To use features in multiple Microsoft Office applications, or to use features in an application or component that doesn't have a project in Visual Studio, you must add a reference to the required PIAs.
In most cases, you should add references to the PIAs that are installed by Visual Studio under the %ProgramFiles(x86)%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\ directory. These versions of the assemblies appear on the Framework tab of the Reference Manager dialog box. For more information, see How to: Target Office applications through primary interop assemblies.
If you've installed and registered the PIAs in the global assembly cache, these versions of the assemblies appear on the COM tab of the Reference Manager dialog box. Avoid adding references to these versions of the assemblies, because there are some development issues that can occur when you use them. For example, if you've registered different versions of the PIAs in the global assembly cache, your project will automatically bind to the version of the assembly that was registered last, even if you specify a different version of the assembly on the COM tab of the Reference Manager dialog box.
Some assemblies are added to a project automatically when an assembly that references them is added. For example, references to the Office.dll and Microsoft.Vbe.Interop.dll assemblies are added automatically when you add a reference to the Word, Excel, Outlook, Microsoft Forms, or Graph assemblies.
Primary interop assemblies for Microsoft Office applications
The following table lists the primary interop assemblies that are available for Office 2016, Office 2013 and Office 2010.
To use the features of a Microsoft Office application from an Office project, you must use the primary interop assembly (PIA) for the application. The PIA enables managed code to interact with a Microsoft Office application's COM-based object model.
Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.
When you create a new Office project, Visual Studio adds references to the PIAs that are required to build the project. In some scenarios, you might need to add references to other PIAs (for example, you can use a feature of Microsoft Office Word in a project for Microsoft Office Excel).
This article describes the following aspects of using the Microsoft Office PIAs in Office projects:
For more information about primary interop assemblies, see Primary interop assemblies.
Separate primary interop assemblies to build and run projects
Visual Studio uses different sets of the PIAs on the development computer. These different sets of assemblies are in the following locations:
A folder in the program files directory
This set of the assemblies is used when you write code and build projects. Visual Studio installs these assemblies automatically.
The global assembly cache
This set of the assemblies is used during some development tasks, such as when you run or debug projects. Visual Studio doesn't install and register these assemblies; you need to do it yourself.
Primary interop assemblies in the program files directory
The PIAs are automatically added to a location in the file system, outside of the global assembly cache, while you install Visual Studio. When you create a new project, Visual Studio automatically adds references to these copies of the PIAs to your project. Visual Studio uses these copies of the PIAs, instead of the assemblies in the global assembly cache, to resolve type references when you develop and build your project.
When different versions of the PIAs are registered in the global assembly cache, you can face several development issues. The added copies of PIAs will help you to avoid such issues.
For Visual Studio 2017 and later, these copies of the PIAs are installed to following shared locations on the development computer:
%ProgramFiles%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\
(or %ProgramFiles(x86)%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\ on 64-bit operating systems)
For older versions of Visual Studio, these PIAs will be installed to the Visual Studio Tools for Office\PIA folder under the %ProgramFiles% folder for that version of Visual Studio. For Example: %ProgramFiles(x86)%\Microsoft Visual Studio 14.0\Visual Studio Tools for Office\PIA\
Primary interop assemblies in the global assembly cache
To perform certain development tasks, the PIAs must be installed and registered in the global assembly cache on the development computer. Typically, the PIAs are installed automatically when you install Office on the development computer. For more information, see Configure a computer to develop Office solutions.
The Office PIAs aren't required on end-user computers to run Office solutions. For more information, see Design and create Office solutions.
Use features of multiple Microsoft Office applications in a single project
Every Office project template in Visual Studio is designed to work with a single Microsoft Office application. To use features in multiple Microsoft Office applications, or to use features in an application or component that doesn't have a project in Visual Studio, you must add a reference to the required PIAs.
In most cases, you should add references to the PIAs that are installed by Visual Studio under the %ProgramFiles(x86)%\Microsoft Visual Studio\Shared\Visual Studio Tools for Office\PIA\ directory. These versions of the assemblies appear on the Framework tab of the Reference Manager dialog box. For more information, see How to: Target Office applications through primary interop assemblies.
If you've installed and registered the PIAs in the global assembly cache, these versions of the assemblies appear on the COM tab of the Reference Manager dialog box. Avoid adding references to these versions of the assemblies, because there are some development issues that can occur when you use them. For example, if you've registered different versions of the PIAs in the global assembly cache, your project will automatically bind to the version of the assembly that was registered last, even if you specify a different version of the assembly on the COM tab of the Reference Manager dialog box.
Some assemblies are added to a project automatically when an assembly that references them is added. For example, references to the Office.dll and Microsoft.Vbe.Interop.dll assemblies are added automatically when you add a reference to the Word, Excel, Outlook, Microsoft Forms, or Graph assemblies.
Primary interop assemblies for Microsoft Office applications
The following table lists the primary interop assemblies that are available for Office 2016, Office 2013 and Office 2010.
- Visual Studio, в моем случае 2012;
- Microsoft Excel, любая версия начиная с 2003;
- Primary Interop Assemblies (PIA).
Что такое Primary Interop Assemblies или сборки взаимодействия
Для Excel 2003/2007 сборки взаимодействия устанавливаются отдельно. После установки эти сборки появляются в GAC. Начиная с Excel 2010 сборки взаимодействия являются частью Excel и их установка отдельно не требуется.
Создание надстройки
- Microsoft.Office.Interop.Excel
- Extensibility
Заметим, что Microsoft.Office.Interop.Excel имеет несколько версий, при этом главный номер соответствует версии Excel. Например, 11 – это Excel 2003, 12 – Excel 2007 и т.д.. С высокой долей вероятности, сборки взаимодействия для Excel 2007 будут работать и в других версиях, однако не стоит забывать, что различия в функциональности этих сборок все же существуют.
Для создания надстройки необходимо создать класс и реализовать интерфейс ITDExtensibility2. Для последующей регистрации надстройки необходимо пометить класс атрибутом ComVisible(true).
public void OnConnection( object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
Интерфейс предоставляет 5 методов . OnConnection вызывается при загрузки надстройки в Excel . При этом параметр connectMode указывает каким именно образом надстройка была загружена, при запуске Excel автоматически или же вручную, путем активации соответствующего флажка в окне надстроек. Интересным параметром здесь также является application типа object , который содержит ссылку на объектную модель Excel . Приведение этой переменной к типу _ Application позволяет управлять объектной моделью. В нашем случае, мы изменяем строку состояния и устанавливаем в нее текст Hello , world .
Метод OnDisconnection вызывается при выгрузки надстройки, т.е. когда соответствующий флажок снимается в окне надстроек или при закрытии Excel .
Метод OnStartupComplete срабатывает только в том случае, если надстройка настроена на загрузку при запуске Excel , и происходит это после того как Excel загружен. В противном, случае метод не вызывается.
Метод OnBeginShutdown вызывается при закрытии Excel . Метод OnAddinsUpdate срабатывает при загрузке или выгрузке надстройки в Excel .
Надстройка готова, теперь необходимо зарегистрировать ее соответствующим образом. Для этого необходимо выполнить следующие шаги:
- Зарегистрировать полученную DLL с помощью утилиты regasm . exe ;
- Добавить несколько записей в реестр.
Необходимо помнить, что Excel бывает как 32-, так и 64-битный. Таким образом . NET сборку необходимо регистрировать дважды, используя как 32-, так и 64-битную версию утилиты regasm . exe .
Прежде чем зарегистрировать сборку с помощью этой утилиты, посмотрим второй пункт. Для того, чтобы Excel понял, что COM компонент представляет собой именно надстройку для Excel , необходимо добавить новую запись в раздел реестра HKLM \ Software \ Microsoft \ Office \ Excel \ AddIns \. При этом имя нового раздела совпадает с именем класса, реализующего надстройку, включая namespace . Автоматизируем этот процесс. Для этого, добавим к нашему классу два новых статических метода.
var path = Registry .LocalMachine.Name + @"\Software\Microsoft\Office\Excel\AddIns\" + type.FullName;
Registry .SetValue(path, "Description" , "This is the first COM Add-in" , RegistryValueKind .String);
var comAddinsKey = Registry .LocalMachine.OpenSubKey( @"Software\Microsoft\Office\Excel\AddIns\" , true );
Обратим внимание , что методы отмечены аттрибутами ComRegisterFunction и ComUnregisterFunction. Согласно документации, методы, отмеченные этими атрибутами будут вызваны при регистрации сборки с помощью утилиты regasm . exe или с помощью метода RegistrationServices.RegisterAssembly. При этом методы должны быть статичными, возвращать тип void и принимать объект типа Type в качестве единственного аргумента.
Таким образом, метод Register будет вызван при регистрации сборки с помощью утилиты regasm . exe . Сам метод, в свою очередь, добавляет новый подраздел в раздел реестра HKLM\Software\Microsoft\Office\Excel\AddIns\, который содержит информацию о всех COM надстройках.
Registry .SetValue(path, "Description" , "This is the first COM Add-in" , RegistryValueKind .String);
Ключ FriendlyName содержит имя надстройки, а ключ Description – его описание. Здесь можно указать любой текст. Наиболее интересным является ключ LoadBehavior , который указывает способ загрузки надстройки в Excel . Этот ключ имеет несколько возможных значений, однако наиболее интересными являются значения 2 и 3. В первом случает надстройка не будет загружена в Excel при запуске , во втором – будет. Установим этот ключ в значение 3 для того чтобы загружать надстройку каждый раз при запуске Excel автоматически. Заметим, что LoadBehavior является единственным обязательным ключом. В случае его отсутствия, надстройка не будет загружена в Excel и также не будет доступна для загрузки в окне Add-ins.
Метод Unregister , отмеченный атрибутом ComUnregisterFunction , соответственно, удаляет информацию о надстройке из списка, таким образом в Excel она доступна не будет. Метод будет вызван при вызове утилиты regasm . exe с ключом / unregister .
Соберем проект и пробуем зарегистрировать полученную сборку. Для удобства, создадим в папке с надстройкой . bat файл со следующими командами
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe " %~dp0\ ComAddin.dll" /codebase
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe " %~dp0\ ComAddin.dll" /codebase
pause
Соответственно, если сборка предварительно добавлена в GAC , ключ / codebase необходимо опустить.
Сразу заметим, что для регистрации сборки необходимы права администратора. Если вы работаете под обычным пользователем, необходимо запускать скрипт от имени администратора.
Для удаления надстройки, необходимо использовать ключ / unregister . При этом скрипт принимает следующий вид.
C :\ Windows \ Microsoft . NET \ Framework \ v 4.0.30319\ regasm . exe " %~dp0\ ComAddin.dll" / unregister
Запускаем Excel. В строке состояния видим ‘Hello, world’, что свидетельствует о том, что надстройка была успешно загружена.
При этом видим, что имя и описание надстройки имеют значения, добавленные ранее в реестр, а сама надстройка расположена в группе “Active Application Add-ins”, т.е. является активной.
Отладка
Отладка надстройки осуществляется достаточно просто. Для этого необходимо зарегистрировать надстройку, после чего в настройках проекта в разделе Debug указать Excel в качестве программы для запуска.
После чего запускаем отладчик. При этом в окне Output в Visual Studio видим последовательность вызова методов класса.
Читайте также: