Visual studio работа с word

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 Word

Create an application-level Add-in for Microsoft Word. This feature is available to the application itself, regardless of which documents are open.

02/02/2017

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

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

John-Hart

johnhart

jmartens

office-development

office

Walkthrough: Create your first VSTO Add-in for Word

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

[!INCLUDEappliesto_wdallapp]

This walkthrough illustrates the following tasks:

  • Creating a Word VSTO Add-in project.

  • Writing code that uses the object model of Word to add text to a document 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]

  • Microsoft Word

Create the project

To create a new Word 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 a Word VSTO Add-in project.

  6. In the Name box, type FirstWordAddIn.

  7. Click OK.

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

Write code to add text to the saved document

Next, add code to the ThisAddIn code file. The new code uses the object model of Word to add boilerplate text to each saved document. 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 Word. 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 Word 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 VSTO Add-in when it is unloaded. For more information, see Events in Office projects.

To add a paragraph of text to the saved document

  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.Word.ApplicationEvents4_Event.DocumentBeforeSave event, which is raised when a document is saved.

    When the user saves a document, the event handler adds new text at the start of the document.

    C#

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

    VB

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

    [!NOTE]
    This code uses an index value of 1 to access the first paragraph in the xref:Microsoft.Office.Interop.Word._Document.Paragraphs%2A collection. Although Visual Basic and Visual C# use 0-based arrays, the lower array bounds of most collections in the Word object model is 1. For more information, see Write code in Office solutions.

  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_DocumentBeforeSave event handler with the xref:Microsoft.Office.Interop.Word.ApplicationEvents4_Event.DocumentBeforeSave event.

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

    To modify the document 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.Word.Application object, which represents the current instance of Word.

  • The Doc parameter of the event handler for the xref:Microsoft.Office.Interop.Word.ApplicationEvents4_Event.DocumentBeforeSave event. The Doc parameter is a xref:Microsoft.Office.Interop.Word.Document object, which represents the saved document. For more information, see Word 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 Word 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 Word, save the active document.

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

    This text was added by using code.

  4. Close Word.

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 Word 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 Word, 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 Word VSTO Add-ins: Word solutions.

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

  • Customizing the UI of Word, 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 Word: Build Office solutions.

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

See also

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

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

The C# programming language includes capabilities that make working with Microsoft Office API objects easier. With the advent of named and optional arguments, introduction of the dynamic type in .NET, and the ability to pass arguments to the reference parameters in COM methods, C# 4.0 quickly became the language of choice for working with COM and Interop objects.

This article talks about office interop objects in C# and how you can use them to interact with Microsoft Word and Microsoft Excel. Code examples are also provided to illustrate the concepts covered.

Prerequisites for working with Interop Objects

Visual Studio 2019 or Visual Studio 2022 must be installed on your computer to work with the code samples demonstrated in this C# tutorial. In this example, we will be using Visual Studio 2022. If you don’t have it installed in your computer, you can download it from here.

As of this writing, Visual Studio 2022 RC 2 has been released. You should also have Microsoft Office Excel 2007 or Microsoft Office Word 2007 (or their later versions) installed on your computer.

Read: Code Refactoring Tips for C#.

How to Create a New Console Application in Visual Studio

In this section we will examine how we can create a new console application project in Visual Studio 2022. Assuming Visual Studio 2022 is installed on your system, adhere to the steps given below to create a new Console Application project:

  • Start the Visual Studio 2022 IDE.
  • Click on “Create new project.
  • In the “Create new project” page, select C# in the language drop down list, Windows from the Platforms list and Console from the “Project types” list.
  • Select Console App (.NET Framework) from the project templates displayed.

Create New Project in Visual Studio

  • Click Next.
  • In the “Configure your new project” screen, specify the project’s name and the location where you would want the project to be created.
  • Before you move on to the next screen, you can optionally select the “Place solution and project in the same directory” checkbox.

Configure Visual Studio Projects

  • Click Next.
  • In the Additional Information screen, specify the Framework version you would like to use. We will use .NET Framework 4.8 in this example.

Configure VS Projects

  • Click Create to complete the process.

This will create a new .NET Framework Console application project in Visual Studio 2022. We will use this project in the sections that follow.

Install NuGet Packages

Install the following libraries from NuGet using the NuGet Package Manager or from the NuGet Package Manager Console:

Microsoft.Office.Interop.Word
Microsoft.Office.Interop.Excel

Read: Working with C# Math Operators.

How to Program Office Interop Objects in C#

In this section we will examine how to work with Office Interop objects and use them to connect to Microsoft Word and Excel and read/write data.

You must add the following using directives in your program for working with Word and Excel respectively when using Office interop objects:

using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;

Working with Excel Interop Objects in C#

To begin, create a new Excel document named Test.xslx as a sample Excel file present in the root directory of the D:> drive. We will use this file in the following example.

You should create an instance of the Application class pertaining to the Microsoft.Office.Interop.Excel library for communicating with Excel. To do this, write the following C# code:

Application excelApplication = new Application();

The next step is to create an instance of the Workbook class to access a Workbook in Excel. You can create an instance of Workbook using the following code:

Workbook excelWorkBook = excel.Workbooks.Open(@"D:Test.xslx");

To read the name of the workbook, you can use the Name property of the workbook instance as shown in the code snippet given below:

string workbookName = excelWorkBook.Name;

The following code listing illustrates how you can display the value of the first cell of the first worksheet of the Excel document:

int worksheetcount = excelWorkBook.Worksheets.Count;
if (worksheetcount > 0) {
  Worksheet worksheet = (Worksheet) excelWorkBook.Worksheets[1];
  string worksheetName = worksheet.Name;
  var data = ((Range) worksheet.Cells[row, column]).Value;
  Console.WriteLine(data);
} else {
  Console.WriteLine("No worksheets available");
}

Here’s the complete code listing for your reference:

using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System;
using System.Runtime.InteropServices;

namespace OfficeInteropDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = @"D:Test.xlsx";
            DisplayExcelCellValue(filename, 1, 1);
            Console.Read();
        }

        static void DisplayExcelCellValue(string filename, 
        int row, int column)
        {
            Microsoft.Office.Interop.Excel.Application 
            excelApplication = null;
            try
            {
                excelApplication = new 
                Microsoft.Office.Interop.Excel.Application();
                Workbook excelWorkBook = 
                excelApplication.Workbooks.Open(filename);
                string workbookName = excelWorkBook.Name;
                int worksheetcount = excelWorkBook.Worksheets.Count;

                if (worksheetcount > 0)
                {
                    Worksheet worksheet = 
                   (Worksheet)excelWorkBook.Worksheets[1];
                    string firstworksheetname = worksheet.Name;
                    var data = ((Microsoft.Office.Interop.Excel.Range)
                    worksheet.Cells[row, column]).Value;
                    Console.WriteLine(data);
                }
                else
                {
                    Console.WriteLine("No worksheets available");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (excelApplication != null)
                {
                    excelApplication.Quit();
                    Marshal.FinalReleaseComObject(excelApplication);
                }
            }
        }
    }
}

Refer to the code listing given above. Note, the finally block of the DisplayExcelCellValue method. The Quit method is called on the Excel application instance to stop the application. Finally, a call to Marshall.FinalReleaseComObject sets the reference counter of the Excel application instance to 0.

The following code listing illustrates how you can create a new Excel document using Office Interop in C#. Note how a new workbook has been created:

static void CreateExcelDocument() 
{
	Microsoft.Office.Interop.Excel.Application excelApplication = null;

	try {
		excelApplication = new 
            Microsoft.Office.Interop.Excel.Application();
		Workbook excelWorkBook = excelApplication.Workbooks.Add();
		Worksheet worksheet = (Worksheet) excelWorkBook.Worksheets[1];
		worksheet.Cells[1, 1] = "Product Id";
		worksheet.Cells[1, 2] = "Product Name";
		worksheet.Cells[2, 1] = "1";
		worksheet.Cells[2, 2] = "Lenovo Laptop";
		worksheet.Cells[3, 1] = "2";
		worksheet.Cells[3, 2] = "DELL Laptop";
		excelWorkBook.SaveAs(@"D:Test.xls");
	}
	catch(Exception ex) {
		Console.WriteLine(ex.Message);
	}
	finally {
		if (excelApplication != null) {
			excelApplication.Quit();
			Marshal.FinalReleaseComObject(excelApplication);
		}
	}
}

When you run this code, a new Excel document will be created at the path specified with the following content inside:

C# Interop Objects Tutorial

Read: Working with Strings in C#.

Working with Word Interop Objects in C#

To work with Microsoft Word, you would need to create an instance of Microsoft.Office.Interop.Word.Application. Like Excel, this instance would be used to communicate with a Word document.

Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();

The next step is to create a document instance using the Documents property of the Microsoft.Office.Interop.Word.Application instance we just created, as shown in the C# code snippet given below:

wordApplication.Documents.Add();

Next, you can create a paragraph and add some text to it using the as shown in the code snippet shown below:

var paragraph = document.Paragraphs.Add();
paragraph.Range.Text = "This is a sample text to demonstrate how Interop works...";

Then you can save the Word document using this code:

wordApplication.ActiveDocument.SaveAs(@"D:Test.doc", WdSaveFormat.wdFormatDocument);

Here is the complete code listing showing how to work with Microsoft Word Interop Objects in C# for your reference:

using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System;
using System.Runtime.InteropServices;

namespace OfficeInteropDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = @"D:Test.doc";
            CreateWordDocument(filename);
            Console.Read();
        }

        static void CreateWordDocument(string filename)
        {
            Microsoft.Office.Interop.Word.Application 
            wordApplication = null;
            try
            {
                wordApplication = new 
                Microsoft.Office.Interop.Word.Application();
                var document = wordApplication.Documents.Add();
                var paragraph = document.Paragraphs.Add();
                paragraph.Range.Text = "This is a sample text to 
                demonstrate how Interop works...";
                wordApplication.ActiveDocument.SaveAs(filename, 
                WdSaveFormat.wdFormatDocument);
                document.Close();

            }
            finally
            {
                if (wordApplication != null)
                {
                    wordApplication.Quit();
                    Marshal.FinalReleaseComObject(wordApplication);
                }
            }
        }
    }
}

To read a Word document and display each word of the document you can use the following C# code:

static void ReadWordDocument(string filename)
        {
            Microsoft.Office.Interop.Word.Application 
            wordApplication = null;
            try
            {
                wordApplication = new 
                Microsoft.Office.Interop.Word.Application();
                Document document = 
                wordApplication.Documents.Open(filename);

                int count = document.Words.Count;
                for (int i = 1; i <= count; i++)
                {
                    string text = document.Words[i].Text;
                    Console.WriteLine(text);
                }
            }
            catch(Exception ex)
            {
                Console.Write(ex.Message);
            }
            finally
            {
                if (wordApplication != null)
                {
                    wordApplication.Quit();
                    Marshal.FinalReleaseComObject(wordApplication);
                }
            }
        }

Note how the Words property of the Word application instance has been used to retrieve the words contained in the document.

C# Interop Objects Tutorial

In this article we have examined how we can access Microsoft Office Interop objects using C#. Since there is still no support for working with Interop objects in .NET Core, we have created a .NET Framework Console Application in this example.

Introduction

For a long time, businesses have relied on Microsoft’s
Office applications to help running their daily routines.
Word is used to write e-mails and letters, Excel does the
calculations, and Outlook communicates. Everyone has seen a
slideshow made with PowerPoint. During the years, Office has
grown, and today the number of applications part of the
suite has grown to over ten.

Although many businesses can run their business with
stock versions of these products, it is common to repeat the
same steps again and again. For instance, sales people might
copy and paste information from their sales system to a Word
document, write their offer, send it out, and then return to
the sales system to mark their offer as done. And then they
start all over again.

As with many other Microsoft products, Office
applications are also highly customizable. In the past few
releases, extending these applications has become easier,
and you as a developer are not anymore limited to writing
COM DLLs with complex interfaces. Today, .NET
developers can also easily get started.

In this article, you are going to learn how you can use
Visual Studio 2008 and .NET to write custom add-ins for
Word. Along the way, you will explore the possibilities for
writing such applications. For instance, you can integrate
databases, web services and even blogs to your add-ins.

Say hello to VSTO

Developing applications for the Office products, and
especially for Office 2003 and 2007, is best done using
Visual Studio Tools for Office, or VSTO. With VSTO in Visual
Studio 2008, you can create different types of applications
that utilize the Office products as a platform. For
instance, you can create application-level add-ins,
document-level customizations, templates, workflows, and so
on. And as you might guess, you can develop your
applications from the convenience of the Visual Studio
IDE.

Love or hate it, the Office 2007 release bought
developers the Ribbon (Figure 1). With VSTO, you can also
create your own customizations to the ribbon, for example by
adding buttons or creating new groups of commands. Although
ribbon customizations are not the focus of this article, it
is important to realize that this kind of user interface is
getting more and more common. Windows 7 also contains a
ribbon interface in many of the built-in applications such
as Paint and Wordpad.

Office applications have had a user interface element
called a task panel for a long time already (Figure 2). With
VSTO, you can create your custom task panels, and for the
purpose of this article, they are a great way to expose the
add-in’s user interface, but more on that shortly.

If you have studied Office application development
before, you might have the impression that such development
work is hard. With previous versions of Visual Studio, this
arguably was the case, as you had to fiddle with different
COM interfaces, primary interoperability assemblies (PIAs),
and so on. But if you are using Visual Studio 2008 and are
targeting Office 2007 applications, things have gotten much
easier.

Installing VSTO usually happens along with Visual Studio.
When selecting the features to be installed, you will also
have the chance to select VSTO components (Figure 3). Note
however, that VSTO is only available from Visual Studio
Professional upwards. It is not available in the Visual
Studio Standard or Expression editions, nor can it be
purchased separately.

Figure 3. VSTO components are part of Visual Studio 2008
Professional and Team editions.

Creating a custom solution for Word

A technology like VSTO is best demonstrated with the help
of a sample application. To demonstrate the possibilities of
expanding Office applications with a custom solution, this
article walks you through in creating an add-in for Word
with VSTO in Visual Studio 2008.

The add-in itself contains a custom task panel. The
purpose of this panel is to let a sales person send quotes
to customers more efficiently. The sales person can simply
enter a customer ID, and automatically fetch customer’s
basic information into the active Word document. The panel
also contains a little utility to convert U.S. dollar amount
to euros using a web service. Finally, once the document is
saved, the add-in posts an update to a public blog. This
way, other sales persons are aware of the updated quote.

To begin developing your custom task panel, you first
need to fire up Visual Studio 2008. Choose to create a new
project (with the File/New/Project menu command), and in the
subsequent New Project dialog box, navigate to the
Office/2007 project type node on the left (Figure 4). From
there, select a Word Add-in, enter a name for your project
(such as WordSalesToolsAddIn), and click OK.

Once Visual Studio has finished creating your project
from the template, you should see a project with several
files and references (Figure 5). For instance, under the
Word folder, you should see a file named ThisAddIn.cs. This
file acts like the Global.asax.cs file in ASP.NET web
applications: the code in the file is executed when the add-
in first loads, and also when add-in is unloaded, i.e. when
Word closes down.

If you run the project immediately after creating it,
Visual Studio will automatically register your add-in so
that Word can load it, and will then start Word. This makes
development and testing very easy. However, unless you have
written additional code to the project, you cannot actually
see anything in Word when you run your project. Even on the
Ribbon, the Add-ins tab (if visible) doesn’t contain any
hints about your creation.

Of course, creating a custom task panel will create
something that’s visible in Word. At this point, you might
be tempted to return to Visual Studio, open the Add New Item
dialog box (Project/Add New Item) and look for a custom task
panel object. Unfortunately, such an object does not exist.
Instead, to create custom task panels for Word and other
compatible Office applications, you need user controls.

Task panels as user controls

To create a new custom task panel for Word, you need to
add a Windows Forms user control to your project. To do
this, open the Add New Item dialog box and select the User
Control template from the Windows Forms group (Figure 6).
Alternatively, you can use the Project menu’s “Add User
Control” command.

Once added, the user control will show as a
blank, gray area in the Visual Studio designer. The next
step would be to add controls to the designer surface. You
will also need a small piece of code in the ThisAddIn.cs
file to register your task panel with Word, and make it
visible. The code is similar to the following:


SalesToolsUserControl userControl =
new SalesToolsUserControl();
CustomTaskPane myCustomTaskPane =
this.CustomTaskPanes.Add(
userControl, “Sales Tools”);
myCustomTaskPane.Visible = true;

This code is added to the ThisAddIn_Startup method in the
ThisAddIn.cs file. In the code, an instance of the user
control (here called SalesToolsUserControl) is created, and
then it is added to the list of custom task panes that Word
controls. Finally, the pane is shown on the screen.

Implementing the functionality for the add-in

Once you have the basic user control skeleton created for
your custom task pane, it is time to add some functionality.
You can easily design the user interface of your pane in
Visual Studio, as a full-blown form designer is already
there. By default, Word sets the pane’s width to equal 200
pixels, with a height dependent on the size of Word’s main
window. You might wish to set the width of your user control
to equal 200 pixels so that designing would be easier.

Figure 7 shows the designed user interface for the sample
user control. Overall, the user interface itself is very
basic, but it’s the underlying code that makes the add-in
useful. The first feature in the add-in allows the user to
type in a customer ID, and then the add-in will fetch that
customer’s details from the Northwind SQL Server sample
database, and add them to the active Word document.

Figure 7. The sample application’s task panel in Visual Studio designer.
The code to fetch the details is straightforward: an SQL
connection is opened, a command is executed, and finally a
SqlDataReader object is used to fetch the results of the
query: string connStr = Properties.Settings.


Default.DatabaseConnection;
SqlConnection conn = new SqlConnection(
connStr);
try
{
conn.Open();
string sql = “SELECT [companyname], “+
“[contactname], [address], [city], ” +
“[region], [postalcode] “+
“FROM [customers] ” +
“WHERE [customerid] = @custid”;
SqlCommand cmd = new SqlCommand(
sql, conn);
cmd.Parameters.AddWithValue(
“@custid”, customerId);
try
{
SqlDataReader reader =
cmd.ExecuteReader();
try
{
if (reader.Read())
{
CustomerDetails cust =
new CustomerDetails();
cust.CompanyName = reader.GetString(0);
cust.ContactName = reader.GetString(1);
cust.Address = reader.GetString(2);
cust.City = reader.GetString(3);
if (!reader.IsDBNull(4))
{
cust.Region = reader.GetString(4);
}
cust.ZipCode = reader.GetString(5);

// finished
return cust;
}
}

Here, the connection string is read from the add-in’s XML
configuration file, and the given customer ID is passed as a
parameter to the SqlCommand object. The results are returned
in a custom class instance, which contains simple public
properties for each value.

Once the query has been executed, it is time to insert
the results into the active Word document.

This is done
with the following code:


CustomerDetails cust =
DataAccess.GetCustomerDetails(
customerIdTextBox.Text);
// format text
StringBuilder buffer = new StringBuilder();
buffer.AppendLine(cust.CompanyName);
buffer.AppendLine(cust.ContactName);
buffer.AppendLine(cust.Address);
buffer.AppendLine(cust.City);
buffer.AppendLine(cust.Region);
buffer.AppendLine(cust.ZipCode);
// insert text at the current cursor location
Microsoft.Office.Interop.Word.Application
word = Globals.ThisAddIn.Application;
Word.Range selection = word.Selection.Range;
selection.Text = buffer.ToString();

The main interaction with Word happens in the last three
lines of code. The Globals class is a designer-created class
that is part of every Word add-in project, and is created
automatically by Visual Studio when you start the project.
It lives in the hidden ThisAddIn.Designer.cs file. Through
the Globals object, you can access your add-in’s ThisAddIn
class. In turn, this class then contains the Application
reference, which points to Word’s automation interface
master object. The Word object is defined in the
Microsoft.Office.Interop.Word.Application namespace, which
has a rather lengthy name to type. Thus, you might wish to
use the following C# using statements to help you manage the
long names:


using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;
using Microsoft.Office.Tools.Word.Extensions;
using Microsoft.Office.Tools;

These same using statements are available in
ThisAddIn.cs, from which you might wish to copy them to your
user control file.

Converting currency values

The next part of functionality in the sample add-in is
the ability to convert currencies. In this case, the sample
application can take a USD dollar amount, and convert it to
Euros (€). This is done with the help of a free currency
conversion service available at Nimacon.net.

To use this service, you will first need to add a service
reference to the project. This is done easily using the Add
Service Reference dialog box in Visual Studio, launched for
example using the similarly named command in the Project
menu. Once the reference has been added, the following code
can be used to convert a USD amount into Euros:


float usdAmount = float.Parse(usdAmountTextBox.Text);
CurrencyRateService.CurrencyRateServiceClient
client = new CurrencyRateService.CurrencyRateServiceClient();
float euroAmount = client.GetEuroAmount(
“USD”, usdAmount);
MessageBox.Show(“$” + usdAmount + ” is ” +
euroAmount + ” €.”);

First, the code takes the USD amount the user has
entered, and converts the string to a float value. Then, an
instance of the web service client class is constructed
(Visual Studio automatically creates the
CurrencyRateServiceClient class when the service reference
is added). The next step is to make the actual web service
(SOAP) call using the GetEuroAmount method of the service.
This method takes in a currency amount in any supported
currency, and a string specifying which currency the value
is in. The return value is the amount in Euros with the
current exchange rate.

Publishing to a blog

In a corporate setting, sharing information is a
necessity. For instance, if a member of a sales team creates
or updates an important offer, the other members of the team
should know about it. However, letting other people know
that you’ve updated a document is an additional, often
manual step. Why couldn’t the system automatically send a
status update to colleagues whenever an important document
changes?

In the sample application, this need to inform others is
addressed via a blog. Whenever the user saves the offer
(i.e. commits the updates made), the add-in automatically
publishes a new entry on a Google Blogger blog, which is
available at www.blogspot.com (Figure 8). The Blogger
service uses a free HTTP based API, which is divided into
two major parts: authentication with the generic Google
authentication APIs, and the specific Blogger interfaces to
submit blog posts.

Since the focus of this article is in Word add-ins and
not the Google interfaces, only a short description follows.
As mentioned previously, the first part of using the Blogger
service is to authenticate properly. This is done by sending
a HTTP POST request to the authentication URL, and passing
in the username and password for the service. In exchange,
the service returns an authentication token, which must be
passed when submitting a post to the user’s blog with the
Blogger API.

The following is a snippet of the code to authenticate
with the service. The Google developer documentation for the
service is publicly available on the Internet; see the Links
section for details.

WebClient web = new WebClient();
try
{
NameValueCollection postParams =
new NameValueCollection();
postParams.Add(“accountType”, accountType);
postParams.Add(“Email”, email);
postParams.Add(“Passwd”, password);
postParams.Add(“service”, service);
postParams.Add(“source”, sourceApp);
byte[] result = web.UploadValues(
loginUrl, “POST”, postParams);
string resultStr =
Encoding.ASCII.GetString(result);
string[] tokens = resultStr.Split();
bloggerAuthToken = tokens[2].Substring(5);
}
finally
{
web.Dispose();
}

With the authentication token available (the
bloggerAuthToken member at the end of the code snippet), the
next step is to call the actual posting function. This can
be done with code similar to the following:


public static void SubmitBlogPost(
string title, string body)
{
string xml;
MemoryStream xmlStream =
new MemoryStream();
try
{
XmlWriterSettings settings =
new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(
xmlStream, settings);
try
{
writer.WriteStartElement(
“entry”, “http://www.w3.org/2005/Atom”);

writer.WriteEndElement();
}
finally
{
writer.Close();
}
xml = Encoding.ASCII.GetString(xmlStream.ToArray());
}
finally
{
xmlStream.Dispose();
}
WebClient web = new WebClient();
try
{
web.Headers.Add(“Content-Type”, “application/atom+xml”);
web.Headers.Add(“Authorization”, “GoogleLogin auth=” +
bloggerAuthToken);
web.Headers.Add(“GData-Version”, “2”);
web.Encoding = Encoding.UTF8;
string response = web.UploadString(submitUrl, “POST”, xml);
}
finally
{
web.Dispose();
}
}

Here, the code first constructs an XML based Atom entry
that the Blogger service accepts (the actual lines are
omitted for brevity), and then uses a WebClient to connect
to the HTTP service. Note how several custom headers have to
be added to the HTTP request for the Google API to accept
it.

Now that the code to submit a blog entry is in place,
next you need to notice when the Word document is being
saved. The Word object model supports a set of events, and
one of them is called DocumentBeforeSave. You can hook into
this event, and then execute the necessary code to update
the blog whenever the document has been saved.

The logical place to hook into this event is in
ThisAddIn.cs’ ThisAddIn_Startup method. Here is the code to
hook and handle the event:


private void ThisAddIn_Startup(
object sender, System.EventArgs e)
{
userControl = new SalesToolsUserControl();

ApplicationEvents4_DocumentBeforeSaveEventHandler
handler = new ApplicationEvents4_
DocumentBeforeSaveEventHandler(
Application_DocumentBeforeSave);
this.Application.DocumentBeforeSave += handler;
}

private void Application_DocumentBeforeSave(
Microsoft.Office.Interop.Word.Document Doc,
ref bool SaveAsUI, ref bool Cancel)
{
// the document is about to be saved
if (!SaveAsUI)
{
// not saving with a new name
// or for the first time
userControl.PublishSaveToBlog(Doc.FullName);
}
}

Once the event handler has been assigned to the event,
the Application_DocumentBeforeSave method is called each
time the user saves the document. Notice how a presentation
of the active document is passed to the event handler as the
Doc parameter. This object contains a property called
FullName, which is used when creating the blog entry text.
The code in the user control’s PublishSaveToBlog method
looks like the following:


public void PublishSaveToBlog(string filename)
{
if (publishToBlogCheckBox.Checked)
{
BloggerClient.SubmitBlogPost(“Offer updated”,
“The offer “” + filename +
“” has been updated.”);
MessageBox.Show(“Blog entry published!”);
}
}

The end result is a blog entry similar to the one in
Figure 9.

Figure 9. A submitted blog entry by the sample application.

Conclusion

In this article, you saw how you can use Visual Studio
2008 to create add-in applications for the Office 2007 suite
of products, and more specifically Word 2007. Visual Studio
2008 provides ready-made templates for developing such add-
ins, and this gives you a head start. Creating for example a
custom task panel is easy as adding a new user control to
the project, and then registering it with Word.

The sample application (Figure 10) showed you how you can
easily extend Word to transform it to a powerful application
platform: you can access SQL databases, call web services,
and even associate your code with events in Word. From this
perspective, the rule of thumb is that if you can do it
from .NET code, you can also do it from an Office add-in.

If you are looking to build your custom solutions to help
businesses run more efficiently, think about whether you
could integrate the needed functionality into Office
applications like Word, Excel, PowerPoint or Outlook. The
possibilities in both business and personal settings are
many. And once Visual Studio 2010 and Office 2010 become
available, the story will get even better. In the mean time,
let’s empower the office!

Resource Links

Office Development with Visual Studio
Office Developer Center
Word 2007 Developer Reference
Word Object Model Reference
Google Data APIs Overview

About the Author

Jani Järvinen is a software development trainer and
consultant in Finland. He is a Microsoft C# MVP and a
frequent author and has published three books about software
development. He is the group leader of a Finnish software
development expert group at ITpro.fi and a board member of
the Finnish Visual Studio Team System User Group. His blog
can be found at http://www
.saunalahti.fi/janij/. You can send him mail by clicking
on his name at the top of the article.

Like this post? Please share to your friends:
  • Visual studio работа с excel
  • Visual studio использование excel
  • Visual studio visual basic excel
  • Visual studio read excel
  • Visual studio for office excel