Visual studio for office excel

title description ms.date ms.topic dev_langs helpviewer_keywords author ms.author manager ms.technology ms.workload

Walkthrough: Create your first VSTO Add-in for Excel

Create an application-level Add-in for Microsoft Excel. The features that you create are available to the application itself, regardless of which workbooks are open.

08/14/2019

conceptual

VB

CSharp

application-level add-ins [Office development in Visual Studio], creating your first project

Office development in Visual Studio, creating your first project

add-ins [Office development in Visual Studio], creating your first project

Excel [Office development in Visual Studio], creating your first project

John-Hart

johnhart

jmartens

office-development

office

Walkthrough: Create your first VSTO Add-in for Excel

[!INCLUDE Visual Studio]
This introductory walkthrough shows you how to create an application-level Add-in for Microsoft Office Excel. The features that you create in this kind of solution are available to the application itself, regardless of which workbooks are open.

[!INCLUDEappliesto_xlallapp]

[!includeAdd-ins note]

This walkthrough illustrates the following tasks:

  • Creating an Excel VSTO Add-in project for Excel.

  • Writing code that uses the object model of Excel to add text to a workbook when it is saved.

  • Building and running the project to test it.

  • Cleaning up the completed project so that the VSTO Add-in no longer runs automatically on your development computer.

    [!INCLUDEnote_settings_general]

Prerequisites

You need the following components to complete this walkthrough:

  • [!INCLUDEvsto_vsprereq]

  • [!INCLUDEExcel_15_short] or [!INCLUDEExcel_14_short].

Create the project

To create a new Excel VSTO Add-in project in Visual Studio

  1. Start [!INCLUDEvsprvs].

  2. On the File menu, point to New, and then click Project.

  3. In the templates pane, expand Visual C# or Visual Basic, and then expand Office/SharePoint.

  4. Under the expanded Office/SharePoint node, select the Office Add-ins node.

  5. In the list of project templates, select Excel 2010 Add-in or Excel 2013 Add-in.

  6. In the Name box, type FirstExcelAddIn.

  7. Click OK.

    [!INCLUDEvsprvs] creates the FirstExcelAddIn project and opens the ThisAddIn code file in the editor.

Write code to add text to the saved workbook

Next, add code to the ThisAddIn code file. 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. By default, the ThisAddIn code file contains the following generated code:

  • A partial definition of the ThisAddIn class. This class provides an entry point for your code and provides access to the object model of Excel. For more information, see Program VSTO Add-ins. The remainder of the ThisAddIn class is defined in a hidden code file that you should not modify.

  • The ThisAddIn_Startup and ThisAddIn_Shutdown event handlers. These event handlers are called when Excel loads and unloads your VSTO Add-in. 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. For more information, see Events in Office projects.

To add a line of text to the saved workbook

  1. In the ThisAddIn code file, add the following code to the ThisAddIn class. The new code defines an event handler for the xref:Microsoft.Office.Interop.Excel.AppEvents_Event.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.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_ExcelAddInTutorial/ThisAddIn.cs» id=»Snippet1″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_ExcelAddInTutorial/ThisAddIn.vb» id=»Snippet1″:::

  2. If you are using C#, add the following required code to the ThisAddIn_Startup event handler. This code is used to connect the Application_WorkbookBeforeSave event handler with the xref:Microsoft.Office.Interop.Excel.AppEvents_Event.WorkbookBeforeSave event.

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_ExcelAddInTutorial/ThisAddIn.cs» id=»Snippet2″:::

    To modify the workbook when it is saved, the previous code examples use the following objects:

  • The Application field of the ThisAddIn class. The Application field returns a xref:Microsoft.Office.Interop.Excel.Application object, which represents the current instance of Excel.

  • The Wb parameter of the event handler for the xref:Microsoft.Office.Interop.Excel.AppEvents_Event.WorkbookBeforeSave event. The Wb parameter is a xref:Microsoft.Office.Interop.Excel.Workbook object, which represents the saved workbook. For more information, see Excel object model overview.

Test the project

To test the project

  1. Press F5 to build and run your project.

    When you build the project, the code is compiled into an assembly that is included in the build output folder for the project. Visual Studio also creates a set of registry entries that enable Excel to discover and load the VSTO Add-in, and it configures the security settings on the development computer to enable the VSTO Add-in to run. For more information, see Build Office solutions.

  2. In Excel, save the workbook.

  3. Verify that the following text is added to the workbook.

    This text was added by using code.

  4. Close Excel.

Clean up the project

When you finish developing a project, remove the VSTO Add-in assembly, registry entries, and security settings from your development computer. Otherwise, the VSTO Add-in will continue to run every time that you open Excel on your development computer.

To clean up the completed project on your development computer

  1. In Visual Studio, on the Build menu, click Clean Solution.

Next steps

Now that you have created a basic VSTO Add-in for Excel, you can learn more about how to develop VSTO Add-ins from these topics:

  • General programming tasks that you can perform in VSTO Add-ins: Program VSTO Add-ins.

  • Programming tasks that are specific to Excel VSTO Add-ins: Excel solutions.

  • Using the object model of Excel: Excel object model overview.

  • Customizing the user interface (UI) of Excel, for example, by adding a custom tab to the Ribbon or creating your own custom task pane: Office UI customization.

  • Building and debugging VSTO Add-ins for Excel: Build Office solutions.

  • Deploying VSTO Add-ins for Excel: Deploy an Office solution.

See also

  • Office solutions development overview (VSTO)
  • Excel solutions
  • Program VSTO Add-ins
  • Excel object model overview
  • Office UI customization
  • Build Office solutions
  • Deploy an Office solution
  • Office project templates overview

Предыстория

Все началось около четырех лет назад. Работая над очередным проектом по автоматизации бизнес-процессов для крупной российской сети розничной торговли, я заинтересовался разработкой надстроек для офисных приложений, в частности, для 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, поэтому создание нового проекта занимает буквально секунды.

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

<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="TaskPaneApp">
  <Id>11111111-1111-1111-1111-111111111111</Id>
  <Version>1.0.1</Version>
  <ProviderName>WavePoint Co. Ltd.</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="XLTools.net Data Cleaning for Excel" />
  <Description DefaultValue=" Clean bulk data fast: remove extra spaces, change text case, convert text format to numbers, etc."/>
  <IconUrl DefaultValue="~remoteAppUrl/App/DataCleansing/Images/Logo32.png"></IconUrl>
  <SupportUrl DefaultValue="http://xltools.net/excel-apps/data-cleaning-app/"></SupportUrl>
  <Capabilities>
    <Capability Name="Workbook" />
  </Capabilities>
  <DefaultSettings>
    <SourceLocation DefaultValue="~remoteAppUrl/App/DataCleansing/Home.html" />
  </DefaultSettings>
  <Permissions>ReadWriteDocument</Permissions>
</OfficeApp>

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

  • 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 для дальнейшей работы с ними:

Office.context.document.bindings.addFromPromptAsync(Office.BindingType.Matrix, {
            id: "RangeToClean"
        }, function (asyncResult) {
            if (asyncResult.status == "failed") {
                    // Some specific code here
            }
            else {
                    // Some specific code here
            }
        });

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

Office.select("bindings#RangeToClean", onBindingNotFound).getDataAsync(
            {},
            doDataCleaning
        );

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

Office.select("bindings#RangeToClean").setDataAsync(range,function (asyncResult) {
            if (asyncResult.status == "failed") {
                    // Some specific code here
            }
            else {
                app.showNotification(UIText.ExecutedSuccessfully, '', 'success');
            }
        }).

Все методы 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 лет опыта внедрения проектов по автоматизации
бизнес-процессов. Работал со множеством российских и
зарубежных компаний. Основатель проекта XLTools.net.

Table of Contents

  • Introduction
  • Building the Sample

You can download the source code from this link Source
Code Link

Introduction

The main purpose of this article is to explain how to create simple Excel and Microsoft Word Add-Ins using Visual
Studio Tools for Office
 (VSTO).
VSTO is available as an add-in tool with Microsoft Visual Studio. Using Visual Studio we can develop our own custom controls for Office tools like Excel, Word and and so on.
In
our demo program We have used Visual Studio 2010 and Office 2007.

Building the Sample

This article explains a few basic things to create our own Custom Add-Ins for Excel and Word as follows.

1. Excel Add-Ins

  • Add text to any Excel selected active Excel cell.
  • Add an image to Excel from our Custom Control.
  • Load data from a database and display the search result data in Excel.

2. Word Add-Ins

  • Export Word to PDF.
  • Add Image to Word Document.
  • Add Table to Word document.

Description

Creating Excel Add-Ins

To create our own Custom Control Add-Ins for Excel.

Step 1

Create a new project and select Office 2007 Excel Add-In as in the following Image. Select your Project Folder and enter your Project Name.

Step 2

Now we can see that the Excel ThisAddIn.Cs file has been created in our project folder and we can find two default methods in this class as in the following image. “ThisAddIn_Startup
In this event we can display our own custom Control Add-Ins to Excel. We can see the details in the code part.

Step 3

Add a new UserControl to your project to create your own Custom Excel Control Add-In.

Right-click your project->Click Add New Item->Add User Control and Name the control as you wish. Add all your Controls and design your user control depending on your requirement.

In our example,We are performing 3 types of actions in User Controls.

  1. Add Text: In this button click event I will insert the text from the Text box to the Active Selected Excel Cell. Using “Globals.ThisAddIn.Application.ActiveCell
    we can get the current active Excel cell. We store the result in an Excel range and now using the range, value and color we can set our own text and colors to the active Excel Cell.

private void btnAddText_Click(object sender, EventArgs e)  

{  

    Excel.Range objRange = Globals.ThisAddIn.Application.ActiveCell;  

    objRange.Interior.Color = Color.Pink; //Active Cell back Color  

    objRange.Borders.Color = Color.Red;// Active Cell border Color  

    objRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;  

    objRange.Value = txtActiveCellText.Text; //Active Cell Text Add  

    objRange.Columns.AutoFit();   

}

2.  Add Image: using
the Open File Dialog we can select our own image that needs to be added to the Excel file. Using the Excel.Shape we can add our selected image to the Excel file.

private void btnAddImage_Click(object sender, EventArgs e)  

        {  

            OpenFileDialog dlg = new OpenFileDialog();  

            dlg.FileName = "*";  

            dlg.DefaultExt = "bmp";  

            dlg.ValidateNames = true;  

            dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";  

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  

            {  

                Bitmap dImg = new Bitmap(dlg.FileName);  

                  Excel.Shape IamgeAdd = Globals.ThisAddIn.Application.ActiveSheet.Shapes.AddPicture(dlg.FileName,  

      Microsoft.Office.Core.MsoTriState.msoFalse,            Microsoft.Office.Core.MsoTriState.msoCTrue,  

          20, 30, dImg.Width, dImg.Height);  

            }  

            System.Windows.Forms.Clipboard.Clear();  

        }

Search and bind Db Data to Excel: Now
we can create our own Custom Search control to be used in Excel to search our data from the database and bind the result to the Excel file.

Creating the table

-- Create Table ItemMaster in your SQL Server - This table will be used for search and bind result to excel.  

CREATE
TABLE
[dbo].[ItemMasters](  

[Item_Code] [varchar](20)
NOT NULL,  

[Item_Name] [varchar](100)
NOT NULL)  

-- insert sample data to Item Master table  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item001','Coke')  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item002','Coffee')  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item003','Chiken Burger')  

INSERT
INTO
[ItemMasters] ([Item_Code],[Item_Name])  

VALUES
('Item004','Potato Fry')

In the button search click event we search for the data from the database and bind the result to an Excel cell using “Globals.ThisAddIn.Application.ActiveSheet.Cells”.
This will add the result to the active Excel sheet.

private
void
btnSearch_Click(
object
sender, EventArgs e)  

{  

    try  

    {  

        System.Data.DataTable dt =
new
System.Data.DataTable();  

        String ConnectionString =
"Data Source=YOURDATASOURCE;Initial Catalog=YOURDATABASENAME;User id = UID;password=password";  

        SqlConnection con =
new
SqlConnection(ConnectionString);  

        String Query =
" Select Item_Code,Item_Name FROM ItemMasters Where Item_Name LIKE '"
+ txtItemName.Text.Trim() + "%'";  

        SqlCommand cmd =
new
SqlCommand(Query, con);  

        cmd.CommandType = System.Data.CommandType.Text;  

        System.Data.SqlClient.SqlDataAdapter sda =
new
System.Data.SqlClient.SqlDataAdapter(cmd);  

        sda.Fill(dt);  

        if
(dt.Rows.Count <= 0)  

        {  

            return;  

        }  

        Globals.ThisAddIn.Application.ActiveSheet.Cells.ClearContents();    

        Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 1].Value2 =
"Item Code";     

        Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 2].Value2 =
"Item Name";     

        for
(int
i = 0; i <= dt.Rows.Count - 1; i++)  

        {     

            Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 1].Value2 = dt.Rows[i][0].ToString();        

            Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 2].Value2 = dt.Rows[i][1].ToString();  

        }  

    }  

    catch
(Exception ex)  

    {  

    }  

}

Step 4

Now we have created our own User Control to be added to our Excel Add-Ins. To add this user control to our Excel Add-In as we have already seen that the Excel Addin class “ThisAddIn.Cs” has start and stop events. Using
the Office “CustomTaskpane” we can add our user control to Excel as an Add-In as in the following.

private
Microsoft.Office.Tools.CustomTaskPane customPane;  

private
void
ThisAddIn_Startup(
object
sender, System.EventArgs e)  

{  

    ShowShanuControl();  

}  

public
void
ShowShanuControl()  

{  

    var txtObject =
new
ShanuExcelADDIn();  

    customPane =
this.CustomTaskPanes.Add(txtObject,
"Enter Text");  

    customPane.Width = txtObject.Width;  

    customPane.Visible =
true;  

}

Step 5

Run your program and now we can see our user control has been added in the Excel File as an Add-In.
Next we will see how to create Add-Ins for Word Documents using a Ribbon Control.

Creating Word Add-Ins: 
In my example I have used Visual Studio 2010 and Office 2007.
The following describes how to create our own Custom Control Add-Ins for Word.

Step 1

Create a new project and select Office 2007 Word AddIn as in the following Image. Select your Project Folder and enter your Project Name.

Step 2

Add a new Ribbon Control to your project to create your own Word Control Add-In.

Right-click your project then click Add New Item -> Add Ribbon Control and name the control as you wish. 

Add all your controls and design your user control depending on your requirements. By default in our Ribbon Control we can see a “RibbonGroup”. We can add all our controls to the Ribbon Group. Here
in my example I have changed the Group Label Text to “SHANU Add-In”. I have added three Ribbon Button Controls to the group. We can add an image to the Ribbon Button Controls and set the properties of the Button Control Size as “
RibbobControlSizeLarge”. 

Here I have added three Button Controls for export the Word as a PDF, add an image to Word and add a table to the Word file.

Step 3

Export to PDF File Button Click.

Using the “Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat” we can save the Word document to the PDF file. I have used the Save file dialog to save the PDF file into our selected path.

private
void
btnPDF_Click(
object
sender, RibbonControlEventArgs e)  

{  

    SaveFileDialog dlg =
new
SaveFileDialog();  

    dlg.FileName =
"*";  

    dlg.DefaultExt =
"pdf";  

    dlg.ValidateNames =
true;  

    if
(dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  

    {  

        Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat(dlg.FileName, word.WdExportFormat.wdExportFormatPDF, OpenAfterExport:
true);  

    }              

}

Step 4

Here we will add an image to Word. Using the Open File Dialog we can select our own image to be added to the Word file. Using the “Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture” method we can add our
selected image to the Word file.

private
void
btnImage_Click(
object
sender, RibbonControlEventArgs e)  

{  

    OpenFileDialog dlg =
new
OpenFileDialog();  

    dlg.FileName =
"*";  

    dlg.DefaultExt =
"bmp";  

    dlg.ValidateNames =
true;  

    dlg.Filter =
"Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";  

    if
(dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  

    {  

        Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture(dlg.FileName);  

    }  

}

Step 5

Here we will add a table to Word. Using the “Globals.ThisAddIn.Application.ActiveDocument.Tables” method we can add a table to the Word file. In my example I have created a table with 4 columns and 3 rows.

private
void
button1_Click(
object
sender, RibbonControlEventArgs e)  

{  

    Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(Globals.ThisAddIn.Application.ActiveDocument.Range(0, 0), 3, 4);  

.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorSeaGreen;  

    Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Font.Size = 12;  

    Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Rows.Borders.Enable = 1;  

}

Step 6

Run your program and now you will see your own Ribbon Control has been added to the Word file as an Add-In.

  

You can download the source code from this link Source
Code Link

Microsoft Office is heavily used in most organizations, and Microsoft has provided several ways to extend and customize Office applications. In this article, Darko Martinovic demonstrates how to use C# to create several automation solutions, including custom add-ins.

Office components such as Excel or Word, have a powerful GUI, with many options to automate everyday tasks. In addition, there are a lot of excellent Add-Ins such as Power BI. With such functionality and the ability to use VBA, you may ask yourself why we need Office extensions.

Of course, there are many situations in which you might like to extend Office functionality. For example, to create a routine that:

  • exports data from SQL Server into Excel with custom formatting
  • imports data from Excel into the dataset
  • automatizes Pivot Table creation in Excel
  • customizes writing documents in Word
  • customizes writing e-mail messages in Outlook
  • more…

Microsoft provides a mechanism to accomplish all of these tasks. Office developer tools in Visual Studio let you create .NET Framework applications that extend Office. These applications are also named Office solutions. This article talks about how to develop and distribute such solutions.

In order to start developing you have to set up the environment.

Configure a Computer for Developing Office Solutions

The Office Developer Tools are installed by default as part of Visual Studio.

NOTE: In order to follow examples in the article, you can use any edition, including Visual Studio 2017 Community Edition.

If you customize the Visual Studio installation by selecting which features to install, make sure that Microsoft Office Developer Tools is selected during setup. Alternatively, you can start Visual Studio Installer and select the Office/SharePoint development workload, as shown in the image below.

In addition, you have to Install a version of Office that is supported by the Office developer tools in Visual Studio. Examples in the article are tested with Office 2013/2016. Make sure that you also install the PIAs (Primary Interop Assemblies) for the version of Office that you install. The PIAs are installed with Office by default. If you modify the Office setup, make sure that the .NET Programmability Support feature is selected for the applications you want to target.

To check the installation, start Visual Studio, create a new project and be sure that Office templates are present as shown in the image below.

Choose an Office project type

Office projects are divided into Office and COM Add-ins. The first one usually is marked as ‘new development’, uses WEB templates and JavaScript, requires Office 2016, and targets mainly Office 365. In my opinion, both are worth exploring. This article covers the second one, which is usually divided based on the template you choose. There are Document-level customizations and VSTO Add-ins. VSTO Add-ins are associated with the application itself and Document-level customizations, as the name implies, are associated with a particular document.

Besides that, there is the possibility to include the Office object model in your application by referencing PIA assemblies. The PIA enables the managed code in your solution to interact with the Office application’s COM-based object model. That would be the first example in which we will browsing source code in a Console application. If you would like to create your own startup project, choose C# console application from the list of available templates. After that you can use Visual Studio productivity tool Power Commands to copy references as shown in the image below and paste them in your project.

NOTE: You can add references by choosing Add Reference command from References context menu.

Exporting Data into Excel

Download this solution and then open it in Visual Studio. Make sure that ExportToExcel is selected as the startup project. The purpose of the first demo is to introduce the Excel object model by accomplishing one common task, exporting data from SQL Server tables into Excel. In order to follow the demo, you have to change the application configuration file app.config. In the file enter your instance name where you have restored the AdventureWorks2016 database.

The most important objects in Excel are:

  • Application
  • Workbook
  • Worksheet
  • Range

Microsoft documentation states: “The Application object represents the Excel application. The Application object exposes a great deal of information about the running application, the options applied to that instance, and the current user objects open within the instance.”

NOTE: The source code is located in the ExportToExcel.cs file inside the ExportToExcel project. There is no need to copy the code from the article.

In order to instantiate an application object, you have to include the Microsoft.Office.Interop.Excel namespace. An application object is created by using the following code snippet.

var excelApp = new Application

       {

          Visible = false,

          DisplayAlerts = false,

          DisplayClipboardWindow = false,

          DisplayFullScreen = false,

          ScreenUpdating = false,

          WindowState = XlWindowState.xlNormal

        };

If you add a breakpoint on a line after an application object is created (see the image below) and press F5 to start debugging the project, you will notice that nothing changes. The application is started as hidden because the Visible property is set to false.

In order to prove that the Excel application has started, start Task Manager, and find the Excel application on the list, as shown in the image below.

The Workbook object represents a single workbook within the Excel application. The following snippet is used to create the object:

// Create an Excel workbook instance 

var workbooks = excelApp.Workbooks;

var excelWorkBook = workbooks.Add(Template: Type.Missing);

The Worksheet object is a member of the Worksheets collection. Many of the properties, methods, and events of the Worksheet are identical or similar to members provided by the Application or Workbook objects. Excel provides a Sheets collection as a property of a Workbook object. Each member of the Sheets collection is either a Worksheet or a Chart object. The following snippet is used to create the Worksheet.

var wst = excelWorkBook.Worksheets;

Worksheet excelWorkSheet = null;

// Add a new worksheet to workbook with the Data table name

excelWorkSheet = (Worksheet)wst.Add();

A range object represents a cell, a row, a column, or any kind of selection that contains at least one cell. In order to create Range object, you have to use a snippet like this one

var newRng = excelWorkSheet.Range[excelWorkSheet.Cells[startRow + 1, i],

excelWorkSheet.Cells[endIndex, i]];

The purpose of the first example is to take T-SQL query results as an object of type DataSet and transform that object into an Excel workbook. The T-SQL query, as well as the connection string, are found in the application configuration file app.config. The example uses two tables of the AdventureWorks2016 database, both located in the schema Sales: The SalesOrderHeader table which contains 31K rows and SalesOrderDetail which contains 121K rows. On my machine, the Excel file is created in 25 sec. In order to shorten the example, I reduced number of records in both tables to 1000 by applying SELECT TOP in the app.config file.

Generating an object of the DataSet type is quite a common thing, and I will skip describing this part. In the project, the source code to accomplish that task is located in DataAccess.cs.

After getting an object of the DataSet type, Excel Workbook creation is invoked. This is accomplished in the Export method that is part of static class ExportToExcel. The workbook Is exported to C:TMPFirstTest.xlsx. The workbook looks similar to that shown in the image below.

Every table that is part of the DataSet collection becomes an Excel sheet. The first and the second rows contain some information about the data. The third row contains the column names as well as something called ‘auto-filter’ which I will explain in detail later in the article.

When working with the object of type Range, you may find yourself confused by the Range property names that sound very similar, like Value, Value2, and Text.

Besides that, there is a big difference in performance. Text and Value are much slower than Value2. Value2 represents the cells underlying value, unlike Text which gives you the string representation of the cell. Value differs from Value2 when the cell is formatted as date or currency.

In the Export method, there is a parameter named pasteRange used to test performance. Its default value is true which means that the two-dimensional object based on a DataTable is set as the value of the Excel sheet range.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

if (pasteRange == false)

   {

   // slow! do not use like this

      for (var j = 0; j <= table.Rows.Count 1; j++)

      {

         for (var k = 0; k <= table.Columns.Count 1; k++)

         {

            excelWorkSheet.Cells[j + startRow + 1, k + 1] = table.Rows[j][k];

         }

      }

    }

    else

    {

    // using Value2

       excelWorkSheet.Range[excelWorkSheet.Cells[startRow + 1, 1], excelWorkSheet.Cells[endIndex, table.Columns.Count]].Value2 =

                           General.Convert(table);

     }

You can change the method call by setting pasteRange to false as shown in the snippet below.

Excel.ExportToExcel.Export(pasteRange: false, ds: dataSet, mFileName: fileName, title: name,

errorString: out var error2);

When the value false is passed, it iterates through all columns and rows, setting the values by each cell. It’s is slow and should not be used.

Before setting the range’s property Value2, some formatting is made. This is accomplished by processing the Columns collection of the DataTable object and setting the property to NumberFormat.

DateTime columns are formatted as shown in the snippet below

newRng.NumberFormat =

Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;

So, it depends on the CurrentCulture, and on my machine looks similar to the image below:

You can also format numbers. For columns that are System.Decimal type, formatting is accomplished like the snippet below.

newRng.NumberFormat =

    «#» + Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator

         + «##0» + Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator + «00»;

On my machine, it looks similar to the image shown below:

One feature that I love when working with Excel is to put columns into the auto-filter mode. That means that all discrete values for one particular column are bound to the combo box that represents the column name.

This is accomplished by referencing the row in which the column names are and by calling the AutoFilter method as shown in the snippet below.

// apply auto filter

var firstRow = (Range)excelWorkSheet.Rows[<strong>startRow</strong>];

firstRow.AutoFilter(fRow,

                        Criteria1: Type.Missing,

                        Operator: XlAutoFilterOperator.<strong>xlAnd</strong>,

                        Criteria2: Type.Missing,

                        VisibleDropDown: true);

Finally, to conclude the first example, a sentence about disposing of objects. The proper way to dispose objects is to call Marchal.RelaseComObject. This method is used to explicitly control the lifetime of a COM object used from managed code. You should use this method to free the underlying COM object that holds references to resources in a timely manner or when objects must be freed in a specific order.

COM disposing is a very huge and painful topic and one article is not enough to cover it. Talking about COM disposal is out of scope of the article.

Close the console application if still running and remove the first two rows in the Excel workbook created in the example. This is preparation for the second example.

Importing Data from Excel

The source code for this example is located in the ImportFromExcel project. Set up this project as the Startup Project. This example opens the Excel file generated in the first example, but it can be a different Excel file as well. After opening the file, the code tries to determine how many sheets are in the workbook and the name of every sheet.

This example needs a driver installed, microsoft.ace.oledb.12.0. The driver could be downloaded from the link.

After that, by using the OLEDB provider, every sheet is queried and, as a result, an object of type DataSet is formed. When you have a DataSet object, it is easy to update the database or do whatever else you need to do.

The source code that creates an object of type DataSet is displayed in the snippet below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

using (var myConnection = new OleDbConnection($@»Provider=Microsoft.Ace.OLEDB.12.0;Data Source={fileToRead};Extended Properties=’Excel 12.0 Xml;HDR = YES;'»))

{

using (var dtSet = new DataSet())

{

foreach (var s in dic)

{

Console.WriteLine($» Processing {s} table»);

var myCommand = new OleDbDataAdapter($@»select * from {s};», myConnection);

myCommand.TableMappings.Add(«Table», s);

myCommand.Fill(dtSet);

}

foreach (DataTable t in dtSet.Tables)

{

Console.WriteLine($» Table {t.TableName} has {t.Rows.Count} records»);

}

}

}

It is important that the sheet name is put in parenthesis and that dollar sign is appended at the end. For example, you could query the first sheet by issuing select * from [Sales_SalesOrderDetail$];. As a result, the console window displays the number of records for each table.

Now, is time to make a real Add-in for Excel and that is the third example.

Creating an Excel VSTO Add-In

The third example extends Excel functionality by adding a custom tab with two buttons on the Excel Ribbon, as shown in the image below.

Set SimpleTalkExcelAddIn as the Startup project in the solution. This project has the type of Excel VSTO Add-In. When you create such a project for the first time, a class named ThisAddIn is created and two events are raised. Usually, the generated code looks similar to what is shown in the image below.

The Startup event is raised after the VSTO Add-in is loaded and all the initialization code in the assembly has been run. The event is handled by the ThisAddInStartup method in the generated code file named ThisAddin.cs. The code in the ThisAddInStartup event handler is the first user code to run unless your VSTO Add-in overrides the RequestComAddInAutomationService method. In this case, the ThisAddInStartup event handler is called after RequestComAddInAutomationService.

Similar to the Startup event, there is a ShutDown event. The event is raised when the application domain that your code is loaded in is about to be unloaded. Usually, it means when you close the Excel application.

Accessing the application, workbook and worksheet objects is accomplished slightly different from earlier examples, as shown in the code below.

Excel.Worksheet oSheet;

Excel.Workbook oBook;

Excel.Application oApp;

oApp = Globals.ThisAddIn.Application;

oBook = Globals.ThisAddIn.Application.ActiveWorkbook;

oSheet = Globals.ThisAddIn.Application.ActiveSheet;

You can interact with the Excel application by adding two types of Ribbon as shown in the image below.

In the example, the Ribbon of type Visual Designer is already added and named UsingRibbon. In design mode, the Ribbon looks similar to the image below.

The ribbon control has its own set of properties and events. The control looks similar to any tabbed control and exposes a tabs collection.

When working with Excel VSTO Add-in’s, on the Visual Studio Toolbar there is a special tab in Visual Studio Toolbox. You can access the toolbox, called Office Ribbon Controls, through the View->Toolbox menu. It’s shown in the image below.

In the example, a few controls are already added. Ribbon Tab is a part of Ribbon Control collection. In this example it’s labeled as Simple Talk. After the Label property, the most commonly used property is Position. The property is the type of RibbonPosition which is an interface that holds a string called OfficeId and an enumerator with three possible values:

  • Default
  • BeforeOfficeId
  • AfterOfficeId

If you choose something other than Default, you have to specify the OfficeId as a string value. Usually, this ID is formed from the word ‘Tab’ plus the ‘Label’ shown on Excel main ribbon. For example, if you would like to position the tab before the ‘Insert’ tab, put ‘TabInsert’ as the OfficeId property. Here is an example from this ribbon.

The Group control is a classic container that could hold another control. It also exposes the Position property. In this example, every group control has a button on it. The Button control responds to only one event – the click event. The most important code in this example is in buttons event handlers.

However, before writing anything about what the handler does, I have to make a digression. If you create a brand new Excel VSTO Add-In using Visual Studio template, your first build will fail. Visual Studio will report to you that you have to sign the ClickOnce manifest.

In the example, signing is already accomplished and in the next few sentences, I will explain how.

The project is signed by using the Personal Information Exchange (.pfx) file, although it’s possible to select a certificate from the Store. In order to create a .pfx file, first, you have to create a certificate. This is accomplished by using the Windows SDK utility MakeCert.exe as shown in the snippet below.

MakeCert /n «CN=SimpleTalkExt» /r /h 0 /eku «1.3.6.1.5.5.7.3.3,1.3.6.1.4.1.311.10.3.13» /e «01/16/2174» /sv SimpleTalkExt.pvk SimpleTalkExt.cer /a sha256

After that, another Windows SDK tool named Pvk2Pfx is used. Pvk2Pfx (Pvk2Pfx.exe) is a command-line tool that copies public key and private key information contained in .spc, .cer, and .pvk files to a Personal Information Exchange file. The file is created by issuing following command

pvk2pfx pvk SimpleTalkExt.pvk spc SimpleTalkExt.cer pfx SimpleTalkExt.pfx f

After the file is created, on the project property Signing tab, choose Select from File and select the newly created pfx file. Your build will work correctly. So, time to go back to the main topic.

NOTE: Just like the previous examples, you can see this add-in in action by running the project. Be sure to modify the App.Config file first.

The event handlers for both buttons in the example produce the same result. The result is an Excel workbook. The workbook contains three sheets. The first one a contains data that represents the result of the T-SQL query, the second one is a Pivot table based on data in the first sheet. And the last sheet contains a chart that represents Pivot on the second sheet.

The difference between these two handlers is that the first one shows a form in which the user can specify a connection to SQL Server, T-SQL query, some Pivot options. The form looks similar to that shown in the image below. On the first tab named Connection, you have to specify the instance name and select a database from the list box. This example uses the AdventureWorks2016 database.

On the second tab named Query, you have to specify a T-SQL statement. This example, queries the Sales.SalesHeader table. On the third tab named Fields, you have to specify some Pivot options, like Columns, Rows, Values and so on, as shown in the image below.

Several values are already added to the list boxes, as you see in the image above. Using drag & drop, it is possible to move fields between list boxes similar to Excel. Every table or every query result is not suitable to be pivoted. Furthermore, there is a restriction on the Columns list box. For example, when you try to put SalesOrderID in the Columns list box in Excel, you will receive an Excel message like the one shown in the image below.

Finally, on the Options tab, there are possibilities to define Chart Types, Table Styles and Pivot styles as shown in the image below.

The chart type is an enumerator named xlChartType defined in Microsoft.Office.Core. During loading of the custom user form, the enumerator is set as a data source of the form’s combo box labeled Chart Types, so the user can initially set up the type of chart to see.

NOTE:In Excel it’s possible to change the chart type as well, but the purpose of this example is to show the Excel object model.

Excel exposes 21 ‘Light’ styles, 28 ‘Medium’ styles, and 11 ‘Dark’ styles by default, and you can define your own styles for the table and pivot. When the user has filled everything on the form, and clicks Execute in the current Excel workbook, three sheets are added.

In the first one, the result of the T-SQL query, is displayed very similarly to in the first example, as shown in the image below.

The only difference is that the result is formatted as a table rather than range. This is accomplished by calling function FormatAsTable that is implemented in the project’s General.cs class. The function is implemented as shown in the snippet below.

public static void FormatAsTable(

               Excel.Range sourceRange,

               string tableName,

               string tableStyleName,

               bool isSelected

                )

{

  sourceRange.Worksheet.ListObjects.Add(SourceType: Excel.XlListObjectSourceType.xlSrcRange,Source: sourceRange, LinkSource: Type.Missing, XlListObjectHasHeaders: Excel.XlYesNoGuess.xlYes,Destination: Type.Missing).Name = tableName;

if (isSelected)

   sourceRange.Select();

sourceRange.Worksheet.ListObjects[tableName].TableStyle = tableStyleName;

}

The benefits of formatting ‘as table’ are that column names are frozen in the first row with applied auto-filtering, and there are extra functionalities such as adding Total row by clicking on checkbox, as shown in the image below.

The second sheet contains a pivot table with a slicer object.

You can manipulate fields, applied a filter, and so on. One cool thing is a slicer object, introduced with Excel 2010, which makes it easy to apply a filter.

The pivot table is added by calling the AddPivot function defined in the General.cs static class. The signature of the function looks similar to that shown in the image below.

The AddPivot function uses the PivotTableWizard function which is part of the _Worksheet interface defined in the Microsoft.Office.Interop.Excel namespace. The function call is accomplished as in the snippet below.

//Add a PivotTable to the worksheet.

pivotWorkSheet.PivotTableWizard(

  SourceType: Excel.XlPivotTableSourceType.xlDatabase,

  SourceData: pivotData,

  TableDestination: pivotWorkSheet.Cells[1, 1], // first cell of the pivot table

TableName: pivotTableName

);

Finally, on the third tab, there is a pivot-chart, which is basically the pivot table represented as a chart.

The pivot-chart is added to the workbook by using a wrapper method AddChart defined in the static class General. The most important part of this method is calling the ChartWizard method, which is part of the Chart interface defined in Microsoft.Office.Interop.Excel namespace.

In the introduction of the section I mentioned that there are two buttons on the ribbon form. Both do the same thing. The difference is that information needed to accomplish the task in the second event handler is read from the application configuration file app.config shown in the image below.

Reading from app.config is quite common, and it is accomplished by using ConfigurationManager defined in System.Configuration as shown in the image below.

Changing the values in app.config before and after publishing the result is a little bit different. In order to explain how to achieve this, I have to explain how to publish the result of the project VSTO.

Publishing the project result could be accomplished by using ClickOnce or by creating a Setup project. On the project properties, there is a tab named Publish as shown in the image below.

In addition to specifying the publish and installation folders, you can also specify Prerequisites, Updates, and Options.

When you click on the Prerequisites button, you see a set of options similar to the image below.

When you click on the Update button, you can see a set of options for updates as shown in the image below.

Depending on the options you choose, and after choosing the Publish command from the project context menu, your publishing/installation folder will look to that shown in the image below.

When you browse Application Files, you will notice that the files are separated by the version number. One common thing that you will need to do is to change configuration values, e.g. to change the connection string. This could be done, but after that, you should update the manifest file. On the image below configuration file and manifest file are highlighted.

When you explore the manifest file by using Visual Studio, you will notice that the file is basically an XML file. Part of that file is a description of the configuration file, as shown in the image below.

The result files are protected by hashing. In order to change some values in the configuration file, you have to determine a new hash value. This might be accomplished by using ComputeHashGUI that is part of the article solution. If you set the project as a startup, you will see a simple GUI as shown in the image below.

Usage is easy, first, you have to pick a file and that will be the configuration file. After that, the hash value is calculated by using the hash algorithm selected in the combo box. That hash value is then pasted in the manifest file. And there are a just a few more steps.

First, you have to copy the pfx file to the installation folder as well as the Windows SDK utility called mage.exe. Then you have to sign the manifest file located in the last installation folder by executing

d:publishmage sign d:publishApplication FilesSimpleTalkExcellAddin_1_0_0_0SimpleTalkExcellAddin.dll.manifest certfile «d:publishSimpleTalkExt.pfx»

After that, you have to update the application VSTO file by executing the following command

mage update SimpleTalkExcellAddin.vsto appmanifest «d:publishApplication FilesSimpleTalkExcellAddin_1_0_0_0SimpleTalkExcellAddin.dll.manifest» certfile «D:PUBLISHSimpleTalkExt.pfx»

As a final step, you have to copy the VSTO file to the last installation folder, in this example SimpleTalExcelAddin_1_0_0_0. Of course, all these steps could be automated, but it is out of the scope of the article.

In the solution, there are two other projects. One to define a Word add-in by using the XML Ribbon control, and the other by using Outlook Add-in.

Set TestWordAddIn as the Startup project in Visual Studio. That is the next example.

Working with Word Add-ins

Unlike the previous example in which a Ribbon Designer Control is used, in this section, I will take another approach by utilizing Ribbon XML. So, what is the difference? The Ribbon Designer does not incorporate all facets provided by the OfficeFluentUI model. For example, the Ribbon Designer provides no way to re-purpose built-in commands or work with the BackStage. These things can only be done using Ribbon XML.

When you add a Ribbon (XML) item to a VSTO project from the Add New Item dialog box, Visual Studio automatically adds

  • A Ribbon XML file. This file is used to defined UI elements
  • A Ribbon code file. This file contains the Ribbon class.

In the solution, these two files are named as MyRibbon.xml and MyRibbon.cs.

If you open the MyRibbon.cs file, you will notice that, unlike the previous example in which a Ribbon Designer Control is used, here the class implements an interface called IRibbonExtensibility. The interface is defined as shown in the image below. The interface contains only one method named GetCustomUI. (NOTE : The image is NOT from the project code, it is generated(displayed) with a help of R#-Resharper).

The interface implementation is in the code file and looks similar shown in the following snippet

#region IRibbonExtensibility Members

public string GetCustomUI(string ribbonId)

{

  return GetResourceText(«TestWordAddIn.MyRibbon.xml»);

#endregion

The content of the XML file, returned by GetCustomUI, is used to construct a GUI representation of the ribbon control. You can respond to user actions, such as clicking a button on the ribbon, by creating callback methods. Callback methods resemble events in Windows Forms controls, but they are identified by an attribute in the XML of the UI element and displayed surrounded with red in the image below. You might define an image for a button, as shown highlighted in yellow.

Before exploring the Word Add-in’s functionality, take a look at the Word object model. Similar to Excel, at the top of the object hierarchy, is the Application object. It represents a current instance of Word.

Next in the hierarchy is the Document object, which is basically the most frequently used object. Application objects have a collection named Documents of currently open or created documents.

The Selection object represents the area that is currently selected. When you perform an operation in the Word user interface, such as bolding text, you select, or highlight the text and then apply the formatting.

The Range object represents a contiguous area in a document and is defined by a starting character position and an ending character position. It is not visible, unlike Selection, which is always visible.

Now it is time to start exploring the Add-in functionality. By pressing F5, Word will launch. On the Add-ins tab, there are three buttons, as shown in the image below.

The first button, labeled with Calculate, calculates the number of characters (including hidden) in the current document.

The second button, with the Insert label, inserts a table at the current cursor position. This is accomplished by adding a new table in the ActivDocument.Tables collection, as shown in the snippet below.

var <strong>missing</strong> = Type.Missing;

var currentRange = Globals.ThisAddIn.Application.Selection.Range;

var newTable = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(Range: currentRange, NumRows: 3,

NumColumns: 4, DefaultTableBehavior: ref <strong>missing</strong>, AutoFitBehavior: ref <strong>missing</strong>);

The third button performs spell checking and reports the result by showing a MessageBox dialog. Most of the things that I write about Excel VSTO could be applied to Word VSTO or Outlook VSTO as well.

Now it is time to review the last example. In order to do that set OutLookAddIn as the startup project.

Working with Outlook Add-ins

Most things we are talking about Office VSTO could be applied to Outlook VSTO’s as well. It means that signing the project, then working with ThisAddIn class is almost the same as with Excel or Word VSTO’s.

However, unlike Word or Excel VSTO’s, Outlook VSTO does not raise a ShutDown event. When you create a new Outlook VSTO project, the generated code tells you exactly that.

There is another difference, unlike Excel or Word VSTO’s which allows you to have running instances when you try to debug an OutLook VSTO by running the Outlook client, you receive a message like shown in the image below

At the top of Outlook’s object model hierarchy is the Application object. It represents the Outlook application. The application object has two collection properties, Explorers, and Inspectors. Part of the Explorers collection is the object of type Explorer.

The Explorer object represents a window that displays the contents of a folder that contains items such as e-mail messages, tasks, or appointments. The Inspector object represents a window that displays a single item such as an e-mail message, task, or appointment.

In this example, the Inspector object is used. In the VSTO StartUp event-handler, the following snippet is added in order to respond to the creation of the new e-mail message.

private void ThisAddInStartup(object sender, System.EventArgs e)

{

   _inspectors = Application.Inspectors;

   _inspectors.NewInspector += InspectorsNewInspector;

}

When you create a new task, meeting, contact or e-mail or view existing once, the event is fired. In the event, handler following code is added.

Private void InspectorsNewInspector(Outlook.Inspector inspector)

{

   If (!(inspector.CurrentItem is Outlook.MailItem mailItem)) return;

   if (mailItem.EntryID != null) return;

    mailItem.Subject = @»Mail subject added by using Outlook add-in»;

    mailItem.Body = @»Mail body added by using Outlook add-in»;

}

If the item is a newly created e-mail, then a text is added to e-mail subject and e-mail body.

Finally few words about cleaning up the environment. By choosing File->Options from the main menu, and choosing Add-ins from tabbed menu, you can get the form like shown in the image below.

If you would like to disable an Add-in, just uncheck checkbox that is with Add-ins name. If you would like to remove the Add-in, choose Remove button.

Summary

Browsing Microsoft documentation about Office solutions is a tedious task. There are no pictures and a lot of mistakes. My aim was in writing this article is to provide a set of practical examples that could be easy to follow. The Office solution is a huge topic. In the article, I cover a small part, but I hope quite enough to encourage readers to start exploring the topic.

The solution source code can be found on GitHub here.

18 Sep How to Create an Excel VSTO Add-in

Posted at 01:39h
in Excel VSTO
0 Comments

Howdee! For many years now, being an Excel expert has been almost synonymous with being an expert in writing VBA code. While VBA is a wonderful tool, in 2017 it is a bit dated in my opinion. So, today I want to introduce a new topic, the Excel VSTO add-in. This might be new to some of you, some of you might know what it means, and some may have even experimented with it before. VSTO stands for Visual Studio Tools for Office and is a means to use Microsoft’s Visual Studio IDE (Integrated Development Environment) to create and build your own Excel (and other Microsoft Office applications) add-ins. This has actually been around for several years now, but has yet to be widely adopted. I think this is a mistake by the Excel community.

Why use Visual Studio Tools for Office?

Building your applications using VSTO makes sense for a few reasons. First, Visual Studio is a much more advanced development environment than the VBA editor. Intellisense is much more robust which allows for faster coding and easier debugging. The advanced environment can be intimidating when you’re used to the more simple VBA development interface (it definitely was for me), but it is surprisingly easy to pick up.

Second, you can code in Visual Basic, C#, Python, and even JavaScript (although the base language must be C# or Visual Basic). These languages have significantly more recent support, both by Microsoft and the community at large, than does VBA. Developers are constantly building more libraries that you can use and, with C# in particular, the more popular ones are rarely deprecated. Parsing JSON for example, there are a couple of libraries in VBA to do this, but the support for them is often slow or nonexistent. The Newtonsoft JSON library from NuGet, on the other hand, is incredibly robust (and supports serialization along with parsing) and is actively supported.

Third, the ability to make modern looking interfaces with Winforms and WPF (Windows Presentation Foundation) makes your Excel applications look significantly more attractive than using VBA. Referencing a bit of reason number two here, there are dozens of libraries that extend the functionality of user interfaces and make it easier and faster to build beautiful Excel add-ins. I’ve used a couple of different libraries both professionally and personally and these really make the process fast, easy, and intuitive.

Finally, VSTO offers the ability to extend your Excel applications to the web. You can do this a couple of different ways. You can use task panes to bring the web into your desktop Excel applications, or you can use javascript and create add-ins that run in Excel online. That means you can easily make your add-in cross-platform by utilizing Excel online!

Creating your first Excel VSTO Add-in

Today, I want to just cover the basics of building an Excel VSTO application and I’ll get into some more detailed implementations in later posts. To start you’ll need to download Visual Studio. Any version 2010 or later will work, but I’ll be working with the 2017 community edition (the free version). You can download this here if you need to.

In the install options, I would recommend at least the following three items to get started: Universal Windows Platform development, .Net Desktop development, & Office/Sharepoint development.

excel vsto add-in

With these three you should have plenty to get started developing your Excel add-ins. Once Visual Studio installs and you open it, you’ll see a start screen with a lot of different links on it. This is just the default start screen and you can pick up previous projects from here in the future. To get started with a new project, select “File” in the top left and then “New” and, finally, “Project”.

In the window that opens, select the language you wish to use (I’ll be using C# today). As I mentioned earlier, you must choose either Visual Basic or C# to start your app with, but you can use other languages later if desired. Next, select the Office/SharePoint section. In the center window, you’ll see several options underneath this language for the project template. You can create Web Add-in’s that can be used in Microsoft Online, a VSTO Add-in, or a VSTO template/workbook. Today we will go over the Excel VSTO Add-in, so let’s select that. Don’t forget to name it something useful at the bottom of the window.

excel vsto add-in

Once you click OK, the project will take a minute to build as Visual Studio will go ahead and start the project for you including the code you’ll need to initialize the add-in. This will be contained in the “ThisAddin” file. It contains two methods that handle the startup and shutdown of the add-in so anything you need to do during those times should go inside those methods.

For today’s example, let’s build a simple add-in that will simply read out the address of our current cell and the contents it contains. This will give you a good grasp of how to begin interacting with the Excel object model from a VSTO project. One question you might have asked yourself already, is how can the user control when the code runs? A common approach with VBA code is to assign a macro to a button or some other object within the workbook.

Since we can’t do that in this example, the easiest way to let a user control running the code is to tie it to a ribbon control. To do that, right-click on the project name in the solution explorer. Select “Add” and “New Item”. A new window will pop up. The default selection should be “Ribbon (Visual Designer)” and that just happens to be the one we need. You can rename this ribbon also if you desire and then click “Add” in the bottom right.

Visual Studio will install the Ribbon to the project and open the designer file. If the “Toolbox” is not open on the left side of your screen, open it now by clicking on “View” in the top left and selecting “Toolbox”. Alternatively, you could press Ctrl+alt+X on the keyboard to do this. If you’re clicked on the ribbon designer, you should see “Office Ribbon Controls” as the first option in the toolbox. Inside this group, there is an option for button. Click and drag the button the ribbon interface and it should snap to “group 1” as a new button with the label “button1”.

As with VBA, we can rename these so they display something a little more appropriate by using the “Properties” window. This should appear in the bottom right of your Visual Studio window. Click on the group or button and change the names to something that makes sense to you. Below is a screen grab with the elements we just talked about called out (click to enlarge):

excel vsto add-in

Now, we have our button in place, let’s get to writing some code! From the ribbon designer, you can double click the button to create an event handler just like you would in a VBA user form. The first thing we need to do is create a reference to the active cell so we can return some data about it. To do this, I’m actually going to jump over to the “ThisAddIn” file and enter some code there to demonstrate how to reference code between files in Visual Studio. Switch to the file and add the following code in the ThisAddIn class (if you’re using C#):

[cc lang=”csharp”]
public Excel.Range GetActiveCell()

{

return (Excel.Range)Application.ActiveCell;

}
[/cc]

Next, back in the method we created by double-clicking our button in the Ribbon class, let’s add the following code:

[cc lang=”csharp”]
private void ReadCellDataBtn_Click(object sender, RibbonControlEventArgs e)

{

Range thisCell = Globals.ThisAddIn.GetActiveCell();

MessageBox

.Show(“This cell’s address is: ” + thisCell.Address + ” — And it’s value is: ” + thisCell.Value);

}
[/cc]

If you just enter the code as I displayed above, you’ll get errors. You’ll need to make sure you add the proper using statements to the top of the Ribbon1 class. Those are using Microsoft.Office.Interop.Excel; and using System.Windows;

Once this is done – we can test the Excel VSTO add-in by pressing F5 on our keyboard or clicking “Start” at the top of Visual Studio. This will open an instance of Excel for us to test with. We can type some information into a blank spreadsheet and quickly test if our code works. Please note that you’ll need to add the “Add-ins” ribbon to Excel if you haven’t done so already. This is done by clicking “File”, then “Options”, and finally “Customize Ribbon”. As you can see below, this example is returning the value of our active cell to a message box.

excel vsto add-in

This is all I wanted to cover in this article since, if you’re new to Excel VSTO Add-ins, your head might be hurting right now. Don’t worry, mine was as well when I first started playing with them. My best recommendation for becoming familiar with this approach is to pick a project you’ve done in VBA (the simpler the better) and try to replicate it as an Excel VSTO add-in. That was my first step and I had a lot of mistakes on the way. However, I think this should be the future of working with Microsoft Excel applications for reasons stated at the beginning of this article. Let me know your thoughts below in the comments.

Also, the example file will be available for download as usual if you’re a free member to my site. However, with this type of add-in I am going to zip the Visual Studio project file up and have it available for download. So, if you want to test it out you will need to download Visual Studio before you’re able to. Feel free to drop a question in the comments if you have an issue doing this.

Cheers,

R

Понравилась статья? Поделить с друзьями:
  • Visual studio excel vba
  • Visual studio excel library
  • Visual basic для word скачать
  • Visual basic для word 2016
  • Visual basic для excel цикл