VSTO Excel and Word Add-In C#

Introduction

Excel and MS Word

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 my demo program I have used Visual Studio 2010 and Office 2007.

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

Word Add Ins

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

Code part

Creating Excel Add-Ins

In my example I have used Visual Studio 2010 and Office 2007.

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

Step 1

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

Create new projec

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.

code

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.

code part

In my example, I am 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.
    1. private void btnAddText_Click(object sender, EventArgs e)  
    2. {  
    3.     Excel.Range objRange = Globals.ThisAddIn.Application.ActiveCell;  
    4.     objRange.Interior.Color = Color.Pink; //Active Cell back Color  
    5.     objRange.Borders.Color = Color.Red;// Active Cell border Color  
    6.     objRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;  
    7.     objRange.Value = txtActiveCellText.Text; //Active Cell Text Add  
    8.   
    9.     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.
    1. private void btnAddImage_Click(object sender, EventArgs e)  
    2.         {  
    3.             OpenFileDialog dlg = new OpenFileDialog();  
    4.             dlg.FileName = "*";  
    5.             dlg.DefaultExt = "bmp";  
    6.             dlg.ValidateNames = true;  
    7.   
    8.             dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";  
    9.             if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
    10.             {  
    11.   
    12.                 Bitmap dImg = new Bitmap(dlg.FileName);  
    13.   
    14.                 Excel.Shape IamgeAdd = Globals.ThisAddIn.Application.ActiveSheet.Shapes.AddPicture(dlg.FileName,  
    15.   
    16.         Microsoft.Office.Core.MsoTriState.msoFalse,  
    17.   
    18.         Microsoft.Office.Core.MsoTriState.msoCTrue,  
    19.   
    20.         20, 30, dImg.Width, dImg.Height);  
    21.             }  
    22.             System.Windows.Forms.Clipboard.Clear();  
    23.         }        
  3. 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
    1. -- Create Table ItemMaster in your SQL Server - This table will be used for search and bind result to excel.  
    2.   
    3. CREATE TABLE [dbo].[ItemMasters](  
    4. [Item_Code] [varchar](20) NOT NULL,  
    5. [Item_Name] [varchar](100) NOT NULL)  
    6.   
    7. -- insert sample data to Item Master table  
    8. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])  
    9. VALUES ('Item001','Coke')  
    10.   
    11. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])  
    12. VALUES ('Item002','Coffee')  
    13.   
    14. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])  
    15. VALUES ('Item003','Chiken Burger')  
    16.   
    17. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name])  
    18. 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.
    1. private void btnSearch_Click(object sender, EventArgs e)  
    2. {  
    3.     try  
    4.     {  
    5.         System.Data.DataTable dt = new System.Data.DataTable();  
    6.   
    7.         String ConnectionString = "Data Source=YOURDATASOURCE;Initial Catalog=YOURDATABASENAME;User id = UID;password=password";  
    8.         SqlConnection con = new SqlConnection(ConnectionString);  
    9.         String Query = " Select Item_Code,Item_Name FROM ItemMasters Where Item_Name LIKE '" + txtItemName.Text.Trim() + "%'";  
    10.         SqlCommand cmd = new SqlCommand(Query, con);  
    11.         cmd.CommandType = System.Data.CommandType.Text;  
    12.         System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(cmd);  
    13.         sda.Fill(dt);  
    14.   
    15.         if (dt.Rows.Count <= 0)  
    16.         {  
    17.             return;  
    18.         }  
    19.   
    20.         Globals.ThisAddIn.Application.ActiveSheet.Cells.ClearContents();  
    21.   
    22.         Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 1].Value2 = "Item Code";  
    23.   
    24.         Globals.ThisAddIn.Application.ActiveSheet.Cells[1, 2].Value2 = "Item Name";  
    25.   
    26.         for (int i = 0; i <= dt.Rows.Count - 1; i++)  
    27.         {  
    28.   
    29.             Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 1].Value2 = dt.Rows[i][0].ToString();  
    30.   
    31.   
    32.             Globals.ThisAddIn.Application.ActiveSheet.Cells[i + 2, 2].Value2 = dt.Rows[i][1].ToString();  
    33.         }  
    34.     }  
    35.     catch (Exception ex)  
    36.     {  
    37.     }  

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 usercontrol to Excel as an Add-In as in the following.

  1. private Microsoft.Office.Tools.CustomTaskPane customPane;  
  2.   
  3. private void ThisAddIn_Startup(object sender, System.EventArgs e)  
  4. {  
  5.     ShowShanuControl();  
  6. }  
  7. public void ShowShanuControl()  
  8. {  
  9.     var txtObject = new ShanuExcelADDIn();  
  10.     customPane = this.CustomTaskPanes.Add(txtObject, "Enter Text");  
  11.     customPane.Width = txtObject.Width;  
  12.     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.

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.

Click Add New Item

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”.

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.

  1. private void btnPDF_Click(object sender, RibbonControlEventArgs e)  
  2. {  
  3.     SaveFileDialog dlg = new SaveFileDialog();  
  4.     dlg.FileName = "*";  
  5.     dlg.DefaultExt = "pdf";  
  6.     dlg.ValidateNames = true;  
  7.     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  8.     {  
  9.         Globals.ThisAddIn.Application.ActiveDocument.ExportAsFixedFormat(dlg.FileName, word.WdExportFormat.wdExportFormatPDF, OpenAfterExport: true);  
  10.     }              

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.

  1. private void btnImage_Click(object sender, RibbonControlEventArgs e)  
  2. {  
  3.     OpenFileDialog dlg = new OpenFileDialog();  
  4.     dlg.FileName = "*";  
  5.     dlg.DefaultExt = "bmp";  
  6.     dlg.ValidateNames = true;  
  7.   
  8.     dlg.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png";  
  9.     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  10.     {  
  11.         Globals.ThisAddIn.Application.ActiveDocument.Shapes.AddPicture(dlg.FileName);  
  12.     }  

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.

  1. private void button1_Click(object sender, RibbonControlEventArgs e)  
  2. {  
  3.     Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(Globals.ThisAddIn.Application.ActiveDocument.Range(0, 0), 3, 4);  
  4. .ThisAddIn.Application.ActiveDocument.Tables[1].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorSeaGreen;  
  5.     Globals.ThisAddIn.Application.ActiveDocument.Tables[1].Range.Font.Size = 12;  
  6.   
  7.     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.

Run your program

Up Next
    Ebook Download
    View all
    Learn
    View all