Office add in — Мир ПК

Office add in

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Clone with HTTPS

Use Git or checkout with SVN using the web URL.

Downloading

Want to be notified of new releases in OfficeDev/Office-Add-in-Commands-Samples ?

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio

Latest commit

Files

Permalink

Type Name Latest commit message Commit time
Failed to load latest commit information.
AutoOpenTaskpane
Excel Microsoft.Data.OData security issue Oct 16, 2018
PowerPoint Image» >Fix Typo in manifest file Jul 10, 2017
Simple Update Group id comment. Oct 12, 2017
Tools Merge pull request #19 from stewartadam/patch-1 Jul 24, 2018
Word Removed extra label element Apr 13, 2016
.gitignore Added PowerPoint Sample Feb 12, 2016
FAQ.md Update FAQ.md Apr 25, 2017
Office-Add-in-Commands-Samples.yml Added sample yaml metadata Jan 31, 2018
README.md Updated sample YAML description Jul 23, 2019

Office Add-in Commands Samples

Add-in commands enable developers to extend the Office user interface such as the Office Ribbon to create awesome, efficient to use add-ins. Watch this channel9 video for a complete overview. The examples in this repo show you how to use add-in commands in Excel, Word and PowerPoint add-ins. If you are looking for information about commands for Outlook head to http://dev.outlook.com

Here is how the samples look when running:

Custom Tab (Simple Example)

Existing Tab

Step 1. Setup your environment

Office Desktop: Ensure that you have the latest version of Office installed. Add-in commands require build 16.0.6769.0000 or higher (16.0.6868.0000 recommended). Learn how to Install the latest version of Office applications.

Office Online: There is no additional setup. Please note that support for commands in Office Online for work/school accounts is in preview.

Office for Mac: Ensure that you have build 15.33+

Step 2. Create and validate your manifest

We strongly recommend you to use one of our sample manifests as a starting point, the Simple example is a good one to get going. Once you make it work then you can start making small modifications and test your changes often. If you make modifications, use the Manifest reference as a guide. You can also validate your xml using the Office Add-in Validator **. For Office Windows clients you can also use Runtime Logging to debug your manifest.

You can also use the latest Visual Studio Tools to create and debug your add-in. See next step.

Step 3. Deploy add-in manifest and test the add-in

To test your add-in you must register it with Office. Two methods are currently supported:

Sideload directly to the client

Office Desktop. Sideload your add-in via a network share.

  • Once sideloaded, go to Insert>My Add-ins>Shared Folder and click the Refresh button to ensure the Add-in shows. Do this any time you need to refresh your Ribbon.

Office Online. Open the Add-ins dialog via Insert>Office Add-ins then select [Manage My Add-ins]>Upload My Add-in and upload the manifest file you want to test. To remove a sideloaded add-in you have to clear your HTML LocalStorage

  • Once sideloaded, goto Insert>Office Add-ins and click on the add-in to install it.

Visual Studio F5

  • Make sure you have at least version 16.0.6868.0000 of Office for Windows installed.
  • Make sure you have the latest Visual Studio tools.

Once you have the latest, the new VS templates include support for add-in commands. You can also deploy your add-ins to Windows Desktop clients using F5.

Office Add-Ins для Excel — новые возможности для разработчиков на VBA и VSTO

Предыстория

Все началось около четырех лет назад. Работая над очередным проектом по автоматизации бизнес-процессов для крупной российской сети розничной торговли, я заинтересовался разработкой надстроек для офисных приложений, в частности, для Excel. Стоило мне несколько дней понаблюдать, как сотрудники компании-заказчика тратят уйму времени на рутинные повторяющиеся операции, как у меня появилось множество идей о том, как бы я мог упростить им жизнь.

В то время, у нас, как у разработчиков, было два способа «расширить» Excel под нетиповые задачи:

  • VBA (Visual Basic for Applications);
  • VSTO (Visual Studio Tools for Office).

Думаю, всем разработчикам надстроек для Excel хорошо известны преимущества и недостатки обоих подходов. Большим преимуществом и того, и другого является очень богатое API, позволяющее автоматизировать практически любые задачи. К недостаткам же стоит отнести сложности в установке подобных расширений. Особенно это касается надстроек на базе VSTO, где, зачастую, для инсталляции требуются административные права, получение которых может быть проблематичным для конечных пользователей.

По ряду причин, обсуждение которых выходит за рамки данной статьи, я выбрал для себя вариант с VSTO. Так родилась наша первая надстройка для Microsoft Excel — XLTools. В первую версию продукта вошли инструменты, позволяющие:

  • производить очистку данных в ячейках Excel (удалять лишние пробелы и непечатные символы, приводить регистр к единому виду, и т.д.);
  • преобразовывать таблицы из «двумерного вида» в «плоский» (unpivot);
  • сравнивать данные в столбцах;
  • инструмент для автоматизации всех вышеперечисленных действий.

Появление Office Store

Буквально через год после выхода в свет первой версии надстройки XLTools, мы узнали, что Microsoft запускает новую платформу для продвижения расширений под Office – Office Store. Моя первая мысль – а можем ли мы опубликовать там нашу новую надстройку XLTools? Может к сожалению, а может к счастью, но ответ на этот вопрос – НЕТ. Ни VBA, ни VSTO надстройки не могут быть опубликованы в Office Store. Но стоит ли расстраиваться? К счастью, и здесь ответ – НЕТ, не стоит. Далее я объясню – почему.

Новая концепция Add-Ins для Office

Что же такое Office Store и для чего он нам нужен? Если кратко, то это платформа, которая помогает пользователям и разработчикам искать, скачивать, продавать и покупать надстройки, расширяющие стандартный функционал Office-программ, будь то Excel, Word, Outlook, OneNote или PowerPoint. Если раньше конечным пользователям приходилось искать нужные им надстройки в поисковиках, то сейчас для этого создано единое место – Office Store, доступ к которому возможен прямо из интерфейса офисных программ. Пункт меню «Вставка» -> «Мои надстройки»:

Как мы уже выяснили, опубликовать надстройки, разработанные с использованием VBA или VSTO, в Office Store не получится. С выходом Office 365 и Office Store, Microsoft предложила нам новый способ разработки надстроек с использованием JavaScript API для Office, подразумевающий разработку приложений с использованием веб-технологий, таких как HTML5, CSS, JavaScript и Web Services.

Новый подход обладает как преимуществами, так и недостатками. К преимуществам можно отнести:

  • Простоту установки надстроек из Office Store;
  • Кроссплатформенность из коробки (Excel 2013/2016, Excel Online, Excel for iPad);
  • Возможность использования накопленного опыта веб-разработки (нет необходимости изучать новые технологии, если в команде уже есть веб-разработчики);
  • Готовая инфраструктура, позволяющая продавать надстройки по фиксированной цене или по подписке.

Из недостатков нового подхода могу выделить только один, правда, пока, довольно весомый:

  • Менее богатое API по сравнению с VSTO и VBA (надеюсь, эта проблема будет становиться все менее и менее актуальной с выходом новых версий API).

Разработка надстроек для Excel «по новым правилам»

Итак, с чего же начать, если мы хотим идти в ногу со временем и не упустить новую волну приложений для Office?

Есть два варианта. На текущий момент, разрабатывать приложения на базе JavaScript API мы можем в:

  • Napa – легковесная веб-версия среды разработки для быстрого старта. Будет полезна разработчикам, у которых нет Visual Studio, или тем, кто хочет разрабатывать под операционной системой, отличной от Windows;
  • Visual Studio, начиная с версии 2012, с установленным пакетом Office Developer Tools – более мощная и функциональная среда разработки. Те, кто раньше разрабатывал под VSTO, могут сразу начинать с этого варианта, т.к. Visual Studio у них уже есть.

В данной статье мы рассмотрим разработку с использованием Visual Studio, т.к. сам я использую именно ее. Если Вам интересно попробовать Napa, то ознакомиться с этим инструментом и начать работу с ним можно здесь.

Перед началом разработки стоит также обратить внимание на пару существенных отличий VBA/VSTO надстроек от надстроек для Office Store:

  • Первое отличие заключается в том, что, разрабатывая надстройки на VBA или VSTO, мы могли создавать так называемые «пакетные» продукты, в состав которых входил целый ряд функций. XLTools является отличным примером – надстройка включает в себя множество опций для работы с ячейками, таблицами, столбцами, и т.д. При разработке надстроек для Office Store о таком подходе придется забыть. Планируя разработку, мы должны задуматься над тем, какие именно законченные, изолированные друг от друга функции мы хотим предоставить конечным пользователям. В случае с XLTools, те функции, которые изначально были реализованы в одной надстройке, сейчас представлены пятью отдельными приложениями в Office Store. Такой подход позволяет сделать решения более узконаправленными и повысить количество скачиваний надстроек целевыми пользователями;
  • Второе отличие заключается в разнице между JavaScript API и VSTO/VBA API. Здесь стоит детально изучить возможности, предоставляемые JavaScript API. Для этого советую воспользоваться приложениями API Tutorial (Task Pane) и API Tutorial (Content) от Microsoft.

Разработка надстройки для Excel c использованием Visual Studio и JavaScript API

По умолчанию в Visual Studio есть предустановленные шаблоны проектов для разработки надстроек под Office Store, поэтому создание нового проекта занимает буквально секунды.

Сам проект состоит из файла-манифеста и веб-сайта. Файл манифеста выглядит так:

Основное, что нужно отметить в этом файле:

  • Id – должен быть уникальным для каждого приложения;
  • Version – должна совпадать с версией, указываемой при публикации надстройки через Seller Dashboard (личный кабинет вендора/разработчика, через который осуществляется все управление надстройками, публикуемыми в Office Store);
  • IconUrl и SupportUrl – ссылки должны быть работающими и указывать на расположение картинки-логотипа и страницы с описанием функционала надстройки. В случае, если ссылки будут указаны неверно, манифест не пройдет проверку при публикации через Seller Dashboard;
  • Permissions – определяет уровень доступа надстройки к данным документа. Может принимать такие значения как Restricted, Read document, Read all document, Write document, Read write document;
  • SourceLocation – путь к «домашней» странице приложения на веб-сайте.

Веб-сайт состоит из минимального набора HTML, JavaScript и CSS файлов, необходимых для работы приложения, и по умолчанию предоставляет базовый UI, на основе которого мы можем строить UI для нового решения. Стоит отметить, что одним из требований к сайту является работа по HTTPS. Это означает, что в случае публикации сайта на собственных серверах или на собственном домене, Вам потребуется SSL сертификат. В случае, если Вы планируете использовать, к примеру, Azure Website, этой проблемы можно избежать, т.к. все сайты, развернутые на поддомене azurewebsites.net, по умолчанию доступны как по протоколу HTTP, так и протоколу HTTPS.

Для взаимодействия с данными Excel в JavaScript API предусмотрен стандартный набор методов. Приведу примеры использования лишь некоторых, из числа тех, которые мы использовали при разработке надстройки «XLTools.net Очистка данных»:

  • Добавление «привязки» к выбранному пользователем диапазону ячеек в Excel для дальнейшей работы с ними:
  • Получение данных из диапазона ячеек с использованием ранее созданной «привязки»:
  • Обновление данных в диапазоне ячеек с использованием ранее созданной «привязки»:

Все методы JavaScript API хорошо документированы, их подробное описание можно посмотреть на сайте MSDN.

В зависимости от сценария, обработка данных может происходить как непосредственно на клиенте, т.е. в JavaScript-коде, так и на сервере. Для обработки данных на сервере можно добавить нужные сервисы прямо на сайт, к примеру, с использованием Web API. Общение клиента (надстройки) с веб-сервисами происходит так же, как мы привыкли это делать на любом другом сайте – при помощи AJAX-запросов. Единственное, что нужно учитывать – если Вы планируете использовать сторонние сервисы, расположенные на чужих доменах, то непременно столкнетесь с проблемой same-origin policy.

Публикация надстройки в Office Store

Для публикации надстройки в Office Store Вам необходимо зарегистрироваться на сайте Microsoft Seller Dashboard. После регистрации Вы получите доступ к личному кабинету, где сможете загрузить манифест Вашего приложения и заполнить всю необходимую информацию о нем. Исходя из личного опыта, могу сказать, что проверка приложения после отправки на утверждение занимает обычно от одного до трех рабочих дней. После проверки приложения сотрудниками Microsoft и его одобрения, оно становится доступно для скачивания миллионам пользователей по всему миру через Office Store:

Выводы

В заключение стоит сказать, что надстройки XLTools являются отличным примером того, как можно трансформировать существующие решения на базе технологий VBA/VSTO в кроссплатформенные решения для Office 365. В нашем случае, мы смогли перенести в Office Store добрую половину функций из Desktop-версии XLTools, реализовав шесть отдельных приложений.

Все они в настоящий момент доступны для скачивания через Office Store:

  • XLTools.net SQL запросы — выполнение SQL запросов к данным в таблицах Excel;
  • XLTools.net CSV Export for Excel — позволяет сохранить таблицу в Excel, как CSV файл с указанием нужного разделителя: запятая, точка с запятой или tab;
  • XLTools.net Очистка данных — очистка массива данных: удаление пробелов, изменение регистра текста, перевод текста в числа, т.д.;
  • XLTools.net Unpivot Table for Excel — помогает пользователям Excel трансформировать сложные двумерные таблицы в плоский вид;
  • XLTools.net Отчёты SendGrid — выгрузка отчетов о доставке из аккаунта SendGrid в Excel;
  • XLTools.net Columns Match — сравнение столбцов, поиск столбцов с одинаковыми данными, расчет процента соответствия данных в столбцах.

Так же хотелось бы отметить, что помимо привычных сценариев, с появлением Office Store и Office 365, у нас, как у разработчиков, появились новые возможности по разработке расширений с использованием Office 365 API, позволяющего получить доступ к данным таких сервисов как Mails, Calendars, SharePoint Online, OneDrive for Business и т.д. Кто знает, что мы сможем построить завтра с использованием этих возможностей. Время покажет!

Об авторе

Петр Ляпин -Технический директор ООО «ВейвПоинт»

10 Free Must Have Office Add-ins for Microsoft Office

Previously called Office Apps, Microsoft has renamed them Office Add-ins” and we have a list of some you might want to try in Office 2013 or later.

Microsoft Office provides a great out of the box experience for most users. In addition to being the world’s most popular productivity suite, products in the suite have developed a cottage industry of powerful add-ins that extends the capabilities of each program. We have looked at individual add-ins in the past for Microsoft Office, most recently, the new FindTime Add-in from Microsoft Garage that makes it easy to setup and schedule meetings. There are a lot of add-ins available, but here are some quality free ones to get your feet wet.

10 Microsoft Office Add-ins

Grammarly

The built-in grammar engine in Microsoft Office isn’t as powerful, and it seems. If you’re an author of professional documents or just want to improve your writing, Grammarly can make a positive impact on your grammar and spelling. Other functions include proper use of punctuation and sentence structure. Not all features are available in the free version, but it does a much better job than the built-in spell check and grammar system in Office. When you are ready to review your document, just click the Enable Grammarly button to start checking your document. It’s also worth noting that Grammarly has extensions for Chrome and Firefox.

Google Drive & Dropbox

This is actually a two in one, but since they are both heavily used cloud storage services, they are obvious choices for storing and sharing your Microsoft Office files. Especially with friends and co-workers who don’t use the default OneDrive service. We looked at installing both back in September. Both fully support Office integration and makes it easy to open and view your Office files even if the suite is not installed.

If you live in a city or visiting a foreign country, Uber is becoming the convenient way to get from point A to B. Launched in August 2015, the Uber Add-in for Outlook makes it easy to setup a reminder for your ride to a meeting by adding it to your calendar events. The add-in also works with Outlook on the Web for Office 365 users.

FedEx Package Tracker

If you keep wondering when that package will arrive, then the FedEx Package Tracker is a great way to ease your anxiety. A free download for Outlook and Outlook Online (it’s already built into the service), you can track packages if you live in the Outlook desktop app. The minute you receive an email, you will see Package Tracker appear at the top of the message, just click it to review progress of the package.

Save Outlook.com Messages to OneNote

There are some emails that are just more important than others. The Outlook.com and OneNote Teams realized this then built a cool little add-in that makes it easy to save your emails as OneNote Sections. Check out our article for instructions how to set it up.

FindTime for Microsoft Outlook and Outlook on the Web

The Garage Team at Microsoft released a new add-in for the Microsoft Outlook Personal Information Manager making it easy to find time to set up a meeting with colleagues. A common activity throughout organizations, scheduling a meeting often involves plowing through your Outlook Calendar to find available times. With FindTime, it does most of the work for you.

People Graph for Excel

Tired of boring pie and bar charts? Why not use a people graph infographic instead? I know this would be great for anyone studying social sciences or students in high school who collect data when preparing research projects in social studies. Just as easy as creating a pie chart, just select columns in your spreadsheet containing data, click Insert tab then click People Graph. You can choose from 16 different shapes, multiple color themes, and infographic styles.

DocuSign for Word

Stop printing your Word documents to get them signed, just do it from Word with this cool add-in from DocuSign. You can easily sign the document yourself after editing and have other persons sign it too. Just use the drag and drop functionality to specify tags where recipients need to sign or provide information. DocuSign also works with the latest versions of Word on OS X, iOS, and Office Web Apps. So there is no excuse to get that document signed.

OneNote Publisher for WordPress Add-in

If you use OneNote, you likely blog too and to make it easy, developers of the popular blogging and web publishing platform WordPress make it easy and fast to turn those notes into web pages using the OneNote Plug In for WordPress. Author your posts in OneNote, open the WordPress dashboard, click the OneNote button and your content is added. In WordPress pick the pages you’re ready to publish and that’s it!

Want to make your classroom or presentation more engaging, and then teachers and presenters should look into getting the Poll Everywhere add-in right away. Perfect for creating quizzes with questions and answers it does most of the work for you. Invite persons or a class to respond and view responses appear instantly on the slide in real-time. With PowerPoint on the Web and PowerPoints built in ability to publish to OneDrive, it doesn’t get any easier and fun.

PayPal for Outlook (Bonus Tip)

Need to manage those payments easier? The PayPal’s electronic payment system has a convenient add-in that works with Outlook. Just install it and you can use it to send money to a contact as easy as sending your regular emails.

This is just a list of 10 that you might be interested in trying out. Go to the Microsoft Office Store to find hundreds of free and paid add-ins you can find to make your Office experience even more productive.

What are some of your favorites not covered here? Let us know in the comments section below.

Office add-in ribbons: same tab with 2 addins

I’m trying to make two word add-ins’ groups to appear in the same tab (Tools) but they both create unique tabs (there’s two ‘Tools’ tabs). I saw this video but I’m using the Visual Designer, not XML.

Can I edit the designer code in some way to make this work?

1 Answer 1

Office 2007

Create the Ribbon

  1. Create a 2007 Excel, Outlook, PowerPoint, or Word project in Visual Studio. For the purpose of these steps, create a C# project and name the project RibbonStarterProject.
  2. Add a Ribbon (Visual Designer) item to the project. For the purpose of these steps, accept the default name “Ribbon1”.
  3. Save and close the project.

Create a Class Library Project

  1. Create a new class library project in Visual Studio. For the purpose of these steps, name the project SharedRibbonLibrary.
  2. Add a project reference to the Microsoft.Office.Tools.Common.v9.0 assembly.
  3. On the Project Menu in Visual Studio, click Add Existing Item.
  4. In the Add Existing Item dialog box, browse to the “RibbonStarterProject” project directory, select the Ribbon.cs file, and click Add. Ribbon1.cs is copied to the project directory and appears beneath the project node in Solution Explorer.
  5. Double-click Ribbon1.cs. The Ribbon designer appears.
  6. From the Office Ribbon Controls tab of the Toolbox, drag a button onto group1.
  7. Click button1 to select it.
  8. In the Properties window, set Modifiers to Public. Note: By default, controls that you add to the Ribbon are Internal. That makes them only accessible to code inside the same assembly. However, when you access these controls, you will be accessing them through an assembly reference. Therefore, to reach them from code, you must make them public. More on this soon.
  9. Right-click the Ribbon designer, and then click Properties.
  10. In the Properties window, click the RibbonType property, and then select the Ribbon ID’s of the applications or Outlook Inspector windows in which you want the Ribbon to appear. For more information about this property, see the MSDN reference topic for the RibbonType property.
  11. In Solution Explorer, right-click Ribbon1.cs, and then click View Code.
  12. Change the namespace of the class to “SharedRibbonLibrary”.
  13. Repeat this step for the Ribbon1.designer.cs file.
  14. Compile and save the SharedRibbonLibrary project. You can now use the resulting assembly in any VSTO project that supports the Ribbon.

Consume the Ribbon Customization

  1. Create 2007 Excel, Outlook, PowerPoint, or Word project.
  2. Add a reference to the SharedRibbonLibrary assembly.

Add the following code to the ThisAddin, ThisWorkbook, or ThisDocument class of your project. This code overrides the CreateRibbonExtensibilityObject method and returns the Ribbon to the Office application.

Add a new class to the project. Accept the default name “Class1.cs”.

Replace the code in the Class1 file with the following:

Ok – You are done! You can now access the Ribbon and the button that you added to the Ribbon in your code. Lets try by handling an event in the consuming project.

Handle the Button Click Event

Add the following code to the startup event handler of project.

Add the following event handler to your project:

Run the project.

When the Office application opens, click the Add-Ins tab, and then click your button. A message that says “I can handle events!” appears.

The 2010 implementation actually add’s two Ribbons — one for each Add-In. I believe the article is only applicable to Add-Ins on the same Ribbon in different Office products (eg Word and Excel) not two Excel Add-ins.

Читать еще:  Истек срок действия подписки office 365

Оценка статьи:
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка…

Ссылка на основную публикацию

Похожие публикации

wpDiscuz

contentType technologies createdDate
Запись опубликована в рубрике Администрирование. Добавьте в закладки постоянную ссылку.