Развертывание и публикация надстроек officedeploy and publish office add-ins

Методы и варианты развертывания надстройки Office для тестирования и распространения.

Публикация надстройкиPublish the add-in

Надстройка Office состоит из веб-приложения и файла манифеста.An Office Add-in consists of a web application and a manifest file. Веб-приложение определяет пользовательский интерфейс и функции надстройки, а манифест указывает расположение веб-приложения и определяет параметры и возможности надстройки.The web application defines the add-in’s user interface and functionality, while the manifest specifies the location of the web application and defines settings and capabilities of the add-in.

В процессе разработки надстройки в Visual Studio эта надстройка запускается на локальном веб-сервере ().While you’re developing your add-in in Visual Studio, your add-in runs on your local web server (). Если надстройка работает нужным образом и вы готовы опубликовать ее для доступа других пользователей, выполните следующие действия:When your add-in is working as desired and you’re ready to publish it for other users to access, you’ll need to complete the following steps:

  1. Разверните веб-приложение на веб-сервере или в службе веб-хостинга (например, Microsoft Azure).Deploy the web application to a web server or web hosting service (for example, Microsoft Azure).
  2. Обновите манифест, указав URL-адрес развернутого приложения.Update the manifest to specify the URL of the deployed application.
  3. Выберите метод развертывания надстройки Office и следуйте инструкциям, чтобы опубликовать файл манифеста.Choose the method you’d like to use to deploy your Office Add-in, and follow the instructions to publish the manifest file.

Методы развертыванияDeployment methods

Указанные ниже разделы содержат дополнительные сведения о методах развертывания, которые чаще всего используются для распространения надстроек Office в организации.The following sections provide additional information about the deployment methods that are most commonly used to distribute Office Add-ins to users within an organization.

Сведения о том, как пользователи приобретают, вставляют и запускают надстройки, см. в статье Начало работы с надстройкой Office.For information about how end users acquire, insert, and run add-ins, see Start using your Office Add-in.

С помощью Центра администрирования Office 365 администраторы могут с легкостью развертывать надстройки Office для пользователей и групп в организации. В этом случае надстройки становятся доступны в приложениях Office сразу. Настраивать клиенты не требуется. Используя централизованное развертывание, можно развертывать как внутренние надстройки, так и те, что предоставляются независимыми поставщиками программного обеспечения.The Office 365 admin center makes it easy for an administrator to deploy Office Add-ins to users and groups in their organization. Add-ins deployed via the admin center are available to users in their Office applications right away, with no client configuration required. You can use Centralized Deployment to deploy internal add-ins as well as add-ins provided by ISVs.

Дополнительные сведения см. в разделе Публикация надстроек Office с помощью централизованного развертывания в Центре администрирования Office 365.For more information, see Publish Office Add-ins using Centralized Deployment via the Office 365 admin center.

Каталог приложений SharePoint — это специальное семейство веб-сайтов, в котором можно размещать надстройки Word, Excel и PowerPoint. Так как каталоги SharePoint не поддерживают новые функции надстроек, реализованные в узле манифеста, в том числе команды надстроек, рекомендуем развертывать надстройки в Центре администрирования. Команды надстроек, развернутые с помощью каталога SharePoint, по умолчанию открываются в области задач.A SharePoint app catalog is a special site collection that you can create to host Word, Excel, and PowerPoint add-ins. Because SharePoint catalogs don’t support new add-in features implemented in the node of the manifest, including add-in commands, we recommend that you use Centralized Deployment via the admin center if possible. Add-in commands deployed via a SharePoint catalog open in a task pane by default.

Если вы развертываете надстройки в локальной среде, используйте каталог SharePoint. Дополнительные сведения см. в статье Публикация надстроек области задач и контентных надстроек в каталоге SharePoint.If you are deploying add-ins in an on-premises environment, use a SharePoint catalog. For details, see Publish task pane and content add-ins to a SharePoint catalog.

Примечание

Каталоги SharePoint не поддерживают Office для Mac.SharePoint catalogs do not support Office on Mac. Для развертывания надстроек Office на клиентах Mac необходимо отправить их в AppSource.To deploy Office Add-ins to Mac clients, you must submit them to AppSource.

Развертывание надстроек OutlookOutlook add-in deployment

В локальных и онлайн-средах, в которых не используется служба идентификации Azure AD, надстройки Outlook можно развертывать через сервер Exchange Server.For on-premises and online environments that do not use the Azure AD identity service, you can deploy Outlook add-ins via the Exchange server.

Для развертывания надстроек Outlook требуется следующее:Outlook add-in deployment requires:

  • Office 365, Exchange Online или Exchange Server 2013 или более поздней версииOffice 365, Exchange Online, or Exchange Server 2013 or later
  • Outlook 2013 или более поздней версииOutlook 2013 or later

Чтобы назначить надстройки клиентам, загрузите манифест напрямую из файла или URL-адреса в Центре администрирования Exchange или добавьте надстройку из AppSource. Чтобы назначить надстройки отдельным пользователям, необходимо использовать Exchange PowerShell. Дополнительные сведения см. в статье Установка или удаление надстроек Outlook для организации на сайте TechNet.To assign add-ins to tenants, you use the Exchange admin center to upload a manifest directly, either from a file or a URL, or add an add-in from AppSource. To assign add-ins to individual users, you must use Exchange PowerShell. For details, see Install or remove Outlook add-ins for your organization on TechNet.

Chemistry Add-in for Word

Chemistry Add-in for Word — незаменимая надстройка к Microsoft Office для тех, кто изучает органическую химию. Она  позволяет   студентам, изучающим химию, преподавателям и   исследователям легко  вставлять и изменять информацию о химических веществах, рисовать структурные формулы, создавать наглядные пособия на небывалом прежде уровне. В дополнение к возможности создания формул и двумерных структур, Chem4Word позволяет пользователю обозначать различные «химические зоны » внутри структуры, и создавать    качественные   визуальные изображения химических структур, пригодные для распечатки плакатов и наглядных пособий с возможностью хранить не просто картинки химических структур, формулы, несущие в себе огромное количество различной химической информации.

При установке надстройки в панель инструментов Microsoft Office добавляется еще одна вкладка Chemistry:

Эта вкладка позволяет создать в документе так называемую «химическую зону», в которую можно либо вставить химическую структуру из готовой библиотеки структур, входящей в комплект, либо построить свою химическую формулу (в том числе и на основе шаблонов, которые тоже в программе имеются.

Всю прелесть работы с этой надстройкой могут оценить только химики, безуспешно пытавшиеся конструировать химические формулы при помощи стандартного редактора формул Microsoft Office Word.  Для учителя химии эта надстройка будет лучшим подарком к Дню учителя

Chemistry Add-in for Word полностью бесплатна. Скачать ее можно с сайта

Не отображается диалоговое окно надстройкиAdd-in dialog box cannot be displayed

When using an Office Add-in, the user is asked to allow a dialog box to be displayed.When using an Office Add-in, the user is asked to allow a dialog box to be displayed. The user chooses Allow, and the following error message occurs:The user chooses Allow, and the following error message occurs:

«The security settings in your browser prevent us from creating a dialog box.»The security settings in your browser prevent us from creating a dialog box. Try a different browser, or configure your browser so that and the domain shown in your address bar are in the same security zone.»Try a different browser, or configure your browser so that and the domain shown in your address bar are in the same security zone.»

БраузерыAffected browsers ПлатформыAffected platforms
Internet Explorer, Microsoft EdgeInternet Explorer, Microsoft Edge Office в ИнтернетеOffice on the web

To resolve the issue, end users or administrators can add the domain of the add-in to the list of trusted sites in Internet Explorer.To resolve the issue, end users or administrators can add the domain of the add-in to the list of trusted sites in Internet Explorer. Use the same procedure whether you’re using the Internet Explorer or Microsoft Edge browser.Use the same procedure whether you’re using the Internet Explorer or Microsoft Edge browser.

Важно!

Не добавляйте URL-адрес надстройки в список надежных сайтов, если вы не доверяете надстройке.Do not add the URL for an add-in to your list of trusted sites if you don’t trust the add-in.

Чтобы добавить URL-адрес в список надежных сайтов:To add a URL to your list of trusted sites:

  1. На панели управления перейдите в раздел Свойства браузера > Безопасность.In Control Panel, go to Internet options > Security.
  2. Выберите зону Надежные сайты и нажмите кнопку Сайты.Select the Trusted sites zone, and choose Sites.
  3. Введите URL-адрес из сообщения об ошибке и нажмите кнопку Добавить.Enter the URL that appears in the error message, and choose Add.
  4. Try to use the add-in again.Try to use the add-in again. If the problem persists, verify the settings for the other security zones and ensure that the add-in domain is in the same zone as the URL that is displayed in the address bar of the Office application.If the problem persists, verify the settings for the other security zones and ensure that the add-in domain is in the same zone as the URL that is displayed in the address bar of the Office application.

This issue occurs when the Dialog API is used in pop-up mode.This issue occurs when the Dialog API is used in pop-up mode. To prevent this issue from occurring, use the displayInFrame flag.To prevent this issue from occurring, use the displayInFrame flag. This requires that your page support display within an iframe.This requires that your page support display within an iframe. The following example shows how to use the flag.The following example shows how to use the flag.

Укажите домены, которые необходимо открыть в окне надстройкиSpecify domains you want to open in the add-in window

В Office в Интернете область задач может открывать любой URL-адрес.When running in Office on the web, your task pane can be navigated to any URL. Однако, на платформах для настольных компьютеров в области надстроек ведущего приложения Office открываются только URL-адреса в домене, где размещена начальная страница (указанная в элементе SourceLocation файла манифеста).However, in desktop platforms, if your add-in tries to go to a URL in a domain other than the domain that hosts the start page (as specified in the SourceLocation element of the manifest file), that URL opens in a new browser window outside the add-in pane of the Office host application.

Чтобы переопределить это поведение, укажите все домены, которые должны открываться в окне надстройки, в списке доменов в элементе AppDomains файла манифеста.To override this (desktop Office) behavior, specify each domain you want to open in the add-in window in the list of domains specified in the AppDomains element of the manifest file. URL-адреса в доменах из списка будут открываться в области задач как в классическом Office, так и в Office в Интернете.If the add-in tries to go to a URL in a domain that is in the list, then it opens in the task pane in both Office on the web and desktop. URL-адреса в доменах не из списка будут открываться в новом окне браузера (не в области надстроек) в классическом Office.If it tries to go to a URL that isn’t in the list, then, in desktop Office, that URL opens in a new browser window (outside the add-in pane).

Примечание

Из этого правила есть два исключения:There are two exceptions to this behavior:

  • Это относится только к корневой области надстройки.It applies only to the root pane of the add-in. Если в страницу надстройки внедрен iframe, его можно перенаправить на любой URL-адрес, независимо от того, указан ли он в элементе AppDomains, даже в классической версии Office.If there is an iframe embedded in the add-in page, the iframe can be directed to any URL regardless of whether it is listed in AppDomains, even in desktop Office.
  • Если диалоговое окно открыто с помощью API , URL-адрес, передаваемый методу, должен находиться в том же домене, что и надстройка. Затем диалоговое окно можно перенаправить на любой URL-адрес, независимо от того, указан ли он в элементе AppDomains, даже в классической версии Office.When a dialog is opened with the API, the URL that is passed to the method must be in the same domain as the add-in, but the dialog can then be directed to any URL regardless of whether it is listed in AppDomains, even in desktop Office.

В приведенном ниже примере XML-манифеста главная страница надстройки размещена в домене , указанном в элементе SourceLocation.The following XML manifest example hosts its main add-in page in the domain as specified in the SourceLocation element. В нем также указан домен с помощью элемента AppDomain из списка AppDomains.It also specifies the domain in an AppDomain element within the AppDomains element list. Страница в домене будет открываться в области надстроек даже в классической версии Office.If the add-in goes to a page in the domain, that page opens in the add-in pane, even in Office desktop.

Шаг 3. КодStep 3: Code

Вы не можете научиться водить, читая руководство пользователя, поэтому начните программировать с этого учебника Excel.You can’t learn to drive by reading the owner’s manual, so start coding with this Excel tutorial. Вы будете использовать библиотеку Office JavaScript и немного XML в манифесте надстроек.You’ll be using the Office JavaScript library and some XML in the add-in’s manifest. Нет необходимости запоминать что-либо, потому что на следующих шагах вы получите больше информации об обоих.There’s no need to memorize anything, because you’ll be getting more background about both in a later steps.

Указание доменов, из которых выполняются вызовы API Office.jsSpecify domains from which Office.js API calls are made

Ваша надстройка может выполнять вызовы API Office.js из домена, указанного в элементе SourceLocation файла манифеста.Your add-in can make Office.js API calls from the domain referenced in the SourceLocation element of the manifest file. Если в вашей надстройке есть другие блоки IFrame, которым требуется доступ к API Office.js, добавьте домен этого исходного URL-адреса в список, указанный в элементе AppDomains файла манифеста.If you have other IFrames within your add-in that need to access Office.js APIs, add the domain of that source URL to the list specified in the AppDomains element of the manifest file. Если блок IFrame с источником, не содержащимся в списке , попытается выполнить вызов API Office.js, надстройка получит ошибку об отказе в разрешении.If an IFrame with a source not contained in the list attempts to make an Office.js API call, then the add-in will receive a permission denied error.

Распространенные ошибки и инструкции по устранению неполадокCommon errors and troubleshooting steps

В таблице ниже перечислены распространенные сообщения об ошибках, с которыми могут столкнуться пользователи, и действия, которые можно предпринять для устранения ошибки.The following table lists common error messages that users might encounter and steps that your users can take to resolve the errors.

Сообщение об ошибкеError message РешениеResolution
Ошибка приложения: не удалось подключиться к каталогуApp error: Catalog could not be reached Verify firewall settings.»Catalog» refers to AppSource.Verify firewall settings.»Catalog» refers to AppSource. This message indicates that the user cannot access AppSource.This message indicates that the user cannot access AppSource.
APP ERROR: This app could not be started.APP ERROR: This app could not be started. Close this dialog to ignore the problem or click «Restart» to try again.Close this dialog to ignore the problem or click «Restart» to try again. Убедитесь, что установлены последние обновления Office, или скачайте обновление для Office 2013.Verify that the latest Office updates are installed, or download the update for Office 2013.
Ошибка: объект не поддерживает свойство или метод ‘defineProperty’Error: Object doesn’t support property or method ‘defineProperty’ Убедитесь, что Internet Explorer не работает в режиме совместимости.Confirm that Internet Explorer is not running in Compatibility Mode. Откройте меню «Сервис» > Параметры просмотра в режиме совместимости.Go to Tools > Compatibility View Settings.
Sorry, we couldn’t load the app because your browser version is not supported.Sorry, we couldn’t load the app because your browser version is not supported. Click here for a list of supported browser versions.Click here for a list of supported browser versions. Make sure that the browser supports HTML5 local storage, or reset your Internet Explorer settings.Make sure that the browser supports HTML5 local storage, or reset your Internet Explorer settings. For information about supported browsers, see Requirements for running Office Add-ins.For information about supported browsers, see Requirements for running Office Add-ins.

Обновление надстроек Office, опубликованных с использованием централизованного развертыванияUpdating Office Add-ins that are published via Centralized Deployment

After an Office Add-in has been published via Centralized Deployment, any changes made to the add-in’s web application will automatically be available to all users as soon as those changes are implemented in the web application.After an Office Add-in has been published via Centralized Deployment, any changes made to the add-in’s web application will automatically be available to all users as soon as those changes are implemented in the web application. Changes made to an add-in’s XML manifest file, for example, to update the add-in’s icon, text, or add-in commands, happen as follows:Changes made to an add-in’s XML manifest file, for example, to update the add-in’s icon, text, or add-in commands, happen as follows:

  • Line-of-business add-in: If an admin explicitly uploaded a manifest file when implementing Centralized Deployment via the Office 365 admin center, the admin must upload a new manifest file that contains the desired changes.Line-of-business add-in: If an admin explicitly uploaded a manifest file when implementing Centralized Deployment via the Office 365 admin center, the admin must upload a new manifest file that contains the desired changes. After the updated manifest file has been uploaded, the next time the relevant Office applications start, the add-in will update.After the updated manifest file has been uploaded, the next time the relevant Office applications start, the add-in will update.

    Примечание

    Администратору не нужно удалять бизнес-надстройку, чтобы выполнить обновление.An admin doesn’t need to remove a LOB add-in to make an update. В разделе надстройки администратор может просто выбрать бизнес-надстройку и вызвать эту функцию, нажав кнопку обновить надстройку в правом нижнем углу.In the Add-ins section, the admin can simply choose the LOB add-in and invoke this functionality by pressing the Update add-in button present in the bottom right corner.

  • Надстройка из Магазина Office. Если администратор выбрал надстройку из Магазина Office во время реализации централизованного развертывания в Центре администрирования Office 365, а надстройка в Магазине Office обновилась, то она будет обновлена позже с использованием централизованного развертывания.Office Store add-in: If an admin selected an add-in from the Office Store when implementing Centralized Deployment via the Office 365 admin center, and the add-in updates in the Office Store, the add-in will update later via Centralized Deployment. Надстройка обновится при следующем запуске соответствующего приложения Office.The next time the relevant Office applications start, the add-in will update.

Написание кода для добавления текста в сохраненную книгуWrite code to add text to the saved workbook

Затем добавьте код в файл ThisAddIn.Next, add code to the ThisAddIn code file. Новый код использует объектную модель Excel для вставки стандартного текста в первую строку активного листа.The new code uses the object model of Excel to insert boilerplate text in the first row of the active worksheet. Активным является лист, открытый в момент сохранения книги пользователем.The active worksheet is the worksheet that is open when the user saves the workbook. По умолчанию файл кода ThisAddIn содержит следующий созданный код:By default, the ThisAddIn code file contains the following generated code:

  • Частичное определение класса .A partial definition of the class. Этот класс предоставляет точку входа для кода и обеспечивает доступ к объектной модели Excel.This class provides an entry point for your code and provides access to the object model of Excel. Дополнительные сведения см. в разделе программирование VSTO Add-ins. Остальная часть класса определяется в скрытом файле кода, изменять который не следует.For more information, see Program VSTO Add-ins. The remainder of the class is defined in a hidden code file that you should not modify.

  • Обработчики событий и .The and event handlers. Эти обработчики событий вызываются, когда Excel загружает и выгружает надстройку VSTO.These event handlers are called when Excel loads and unloads your VSTO Add-in. Их можно использовать для инициализации надстройки VSTO в процессе ее загрузки, а также для освобождения используемых надбавкой ресурсов при ее выгрузке.Use these event handlers to initialize your VSTO Add-in when it is loaded, and to clean up resources used by your Add-in when it is unloaded. Дополнительные сведения см. в разделе события в проектах Office.For more information, see Events in Office projects.

Добавление строки текста в сохраненную книгуTo add a line of text to the saved workbook

  1. В файл кода ThisAddIn добавьте в класс указанный ниже код.In the ThisAddIn code file, add the following code to the class. Новый код определяет обработчик событий для события WorkbookBeforeSave , которое возникает при сохранении книги.The new code defines an event handler for the WorkbookBeforeSave event, which is raised when a workbook is saved.

    Когда пользователь сохраняет книгу, обработчик событий добавляет новый текст в начало активного листа.When the user saves a workbook, the event handler adds new text at the start of the active worksheet.

  2. Если используется C#, добавьте в обработчик событий указанный ниже код.If you are using C#, add the following required code to the event handler. Он используется для подключения обработчика событий к событию WorkbookBeforeSave .This code is used to connect the event handler with the WorkbookBeforeSave event.

    Для изменения книги при ее сохранении в приведенных выше примерах кода используются следующие объекты:To modify the workbook when it is saved, the previous code examples use the following objects:

  • Поле класса .The field of the class. Поле возвращает объект Application , который представляет текущий экземпляр Excel.The field returns a Application object, which represents the current instance of Excel.

  • Параметр обработчика событий для события WorkbookBeforeSave .The parameter of the event handler for the WorkbookBeforeSave event. Параметр является объектом Workbook , который представляет сохраняемую книгу.The parameter is a Workbook object, which represents the saved workbook. Дополнительные сведения см. в разделе Общие сведения об объектной модели Excel.For more information, see Excel object model overview.

Расширение возможностей и взаимодействие с клиентами OfficeExtending and interacting with Office clients

Что позволяют надстройки Office в ведущем приложении Office:Office Add-ins can do the following within an Office host application:

  • расширение функциональных возможностей (в любом приложении Office);Extend functionality (any Office application)

  • создание новых объектов (Excel или PowerPoint).Create new objects (Excel or PowerPoint)
     

Расширение функциональных возможностей OfficeExtend Office functionality

Добавить новые возможности в приложения Office можно посредством следующего:You can add new functionality to Office applications via the following:  

  • настраиваемые кнопки ленты и команды меню (в совокупности зовутся «командами надстройки»);Custom ribbon buttons and menu commands (collectively called “add-in commands”)

  • вставляемые области задач.Insertable task panes

Пользовательский интерфейс и области задач указаны в манифесте надстройки.Custom UI and task panes are specified in the add-in manifest.  

Настраиваемые кнопки и команды менюCustom buttons and menu commands  

Вы можете добавлять настраиваемые кнопки ленты и элементы меню на ленту в Office в Интернете и Office для Windows. Благодаря этому пользователям будет проще получать доступ к надстройке непосредственно из приложения Office. С помощью кнопок можно выполнять различные действия, например отображение области задач с пользовательским HTML или выполнение функции JavaScript.You can add custom ribbon buttons and menu items to the ribbon in Office on the web and Windows. This makes it easy for users to access your add-in directly from their Office application. Command buttons can launch different actions such as showing a task pane with custom HTML or executing a JavaScript function.  

Рис. 3. Команды надстройки на лентеFigure 3. Add-in commands in the ribbon

Области задачTask panes  

Для работы с решением пользователи могут использовать не только команды надстройки, но и области задач. В клиентах, не поддерживающих команды надстроек (Office 2013 и Office для iPad), надстройка запускается в виде области задач. Пользователи запускают надстройки области задач с помощью кнопки Мои надстройки на вкладке Вставка.You can use task panes in addition to add-in commands to enable users to interact with your solution. Clients that do not support add-in commands (Office 2013 and Office on iPad) run your add-in as a task pane. Users launch task pane add-ins via the My Add-ins button on the Insert tab.

Рис. 4. Область задачFigure 4. Task pane

Расширение возможностей OutlookExtend Outlook functionality

Надстройки Outlook могут получать доступ к зависящей от контекста информации, предоставляемой элементом, например к адресу или идентификатору для отслеживания, а затем использовать эти данные для доступа к дополнительным сведениям на сервере и в веб-службах с целью повышения удобства работы пользователей. В большинстве случаев надстройка Outlook может без изменений работать в ведущем приложении Outlook, обеспечивая согласованность интерфейса на компьютерах, в Интернете, на планшетах и на мобильных устройствах.Outlook add-ins can access contextual information from the item, such as an address or tracking ID, and then use that data to access additional information on the server and from web services to create compelling user experiences. In most cases, an Outlook add-in runs without modification in the Outlook host application to provide a seamless experience on the desktop, web, and tablet and mobile devices.

Обзор надстроек Outlook см. в статье Общие сведения о надстройках Outlook.For an overview of Outlook add-ins, see Outlook add-ins overview.

Создание новых объектов в документах OfficeCreate new objects in Office documents

Вы можете внедрить веб-объекты, или контентные надстройки, в документы Excel и PowerPoint. Благодаря контентным надстройкам можно интегрировать мультимедиа (например, видеопроигрыватель YouTube или галерею рисунков), полнофункциональные веб-визуализации данных и другое внешнее содержимое.You can embed web-based objects called content add-ins within Excel and PowerPoint documents. With content add-ins, you can integrate rich, web-based data visualizations, media (such as a YouTube video player or a picture gallery), and other external content.

Рис. 5. Контентная надстройкаFigure 5. Content add-in

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделитесь с друзьями:
Технарь
Добавить комментарий

Нажимая на кнопку "Отправить комментарий", я даю согласие на обработку персональных данных и принимаю политику конфиденциальности.