Accessing Microsoft Office InterOP Objects using C# 4.0

No.of Views1902
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  16 Feb 2010 00:02:55
Tag : CSharp , PInvoke
Accessing Microsoft Office InterOP Objects using C# 4.0
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 Objective:

This article will show, how Microsoft office InterOp objects can be access and use in C#. I will be using dynamic type feature of c# 4.0
1. To create and open an Excel Application in VS2010
2. To display list in Active Excel Application.
3. To Create and open a word document in VS2010.
4. To create an icon in word document that will link to selected part of Excel worksheet.

Download Source Code-CS

Step 1:

Image Loading..



Step 2:

Add reference of Microsoft.Office.Interop.Excel and Microsoft.Office.Interop.Word

Image Loading....



Step 3:

Add Name Spaces in Program

{codecitation class="brush: csharp; gutter: true;" width="650px"}

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

{/codecitation}

Step 4:
Create a class called Author. This class is having two properties of dynamic type.

Author class

{codecitation class="brush: csharp; gutter: true;" width="650px"}

public class Authors
{
public dynamic Name { get; set; }
public dynamic NumberOfArticles { get; set; }

}

{/codecitation}


Step 5:

Create a static method to create and return list of authors.

{codecitation class="brush: csharp; gutter: true;" width="650px"}


static dynamic ListofAuthor()

{

List<Authors> _listAuthor = new List<Authors>
{
new Authors(){Name =" Mahesh Chand", NumberOfArticles = 700 },
new Authors () { Name = " Mike Gold", NumberOfArticles = 200},
new Authors () {Name =" Patra " , NumberOfArticles = 50},
new Authors () { Name = "Mamta M ", NumberOfArticles = 38},
new Authors (){ Name = "ShivPrasad K", NumberOfArticles = 80},
new Authors () { Name = "Praveen Masood", NumberOfArticles = 190},
new Authors (){ Name =" Rekha S " , NumberOfArticles = 5}


};

return _listAuthor;
}

{/codecitation}

Step 6:

Displaying in Excel application


Create a static method to create and open Excel sheet. After opening the Excel Sheet, list of author will get inserted in the Excel sheet.

{codecitation class="brush: csharp; gutter: true;" width="650px"}


static void DisplayAuthorsinExcel(dynamic authorlist)

{

dynamic _excelApplication = new Excel.Application();

_excelApplication.Visible = true;

_excelApplication.Workbooks.Add();

Excel._Worksheet worksheet = _excelApplication.ActiveSheet;

worksheet.Cells[1, "A"] = "Name";
worksheet.Cells[1, "C"] = " Number of Articles";

var row = 1;

foreach (var r in authorlist)
{
row++;
worksheet.Cells[row, "A"] = r.Name;
worksheet.Cells[row, "C"] = r.NumberOfArticles;
}

worksheet.Columns[1].AutoFit();
worksheet.Columns[3].AutoFit();

}
}


{/codecitation}


Explanation


1. Type of input parameter is dynamic.
2. Instance of an Excel application is getting created and assigned to the reference of type dynamic.
3. Then one work book is been added to the instance of Excel application.
4. Active work sheet is been assigned to work sheet.
5. We are enumerating to the entire list and adding the Authors in the Excel sheet to display.


Image Loading....

Step 7:

Press F5 to debug and run the application.

Image Loading..

So, successfully we are able to display Authors list in Excel application using C#4.0 features.

Step 8:

Create a word document with Icon Link to selected column of Excel work sheet.

a. Add this line of code at the bottom on DisplayAuthorsinExcelApplication() static method. Below code will copy name of all the authors.

worksheet.get_Range("A1:A8").Copy();

b. Create a static method which will create and open a word document. This document will have an icon. This icon will link to selected portion of active Excel application.

{codecitation class="brush: csharp; gutter: true;" width="650px"}


static void CreateWordDocument()

{

var _wordApplication = new Word.Application();
_wordApplication.Visible = true;
_wordApplication.Documents.Add();
_wordApplication.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);


}


{/codecitation}

Step 9:

Press F5 to run the application. First one Excel sheet will open with the selected values then a word document will open. This document will have an icon that will link to selected part of active excel application.

Image loading....

Figure :01

Image loading.....

Figure :02

Image loading....

Figure :03

Image loading....

Figure :04

For Reference the complete code is as below,

Program.cs

{codecitation class="brush: csharp; gutter: true;" width="650px"}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

namespace OfficeInterOpaccess
{

class Program
{

static void Main(string[] args)
{

dynamic d = ListofAuthor();
foreach ( dynamic k in d)
{
Console.WriteLine(k.Name);
}

DisplayAuthorsinExcel(d);
CreateWordDocument();

Console.Read();

}


static dynamic ListofAuthor()
{
List<Authors> _listAuthor = new List<Authors>
{
new Authors(){Name =" Mahesh Chand", NumberOfArticles = 700 },
new Authors () { Name = " Mike Gold", NumberOfArticles = 200},
new Authors () {Name =" Patra " , NumberOfArticles = 50},
new Authors () { Name = "Mamta M ", NumberOfArticles = 38},
new Authors (){ Name = "ShivPrasad K", NumberOfArticles = 80},
new Authors () { Name = "Praveen Masood", NumberOfArticles = 190},
new Authors (){ Name =" Rekha S " , NumberOfArticles = 5}


};
return _listAuthor;
}



static void DisplayAuthorsinExcel(dynamic authorlist)
{

dynamic _excelApplication = new Excel.Application();
_excelApplication.Visible = true;
_excelApplication.Workbooks.Add();
Excel._Worksheet worksheet = _excelApplication.ActiveSheet;
worksheet.Cells[1, "A"] = "Name";
worksheet.Cells[1, "C"] = " Number of Articles";
var row = 1;
foreach (var r in authorlist)
{
row++;
worksheet.Cells[row, "A"] = r.Name;
worksheet.Cells[row, "C"] = r.NumberOfArticles;
}

worksheet.Columns[1].AutoFit();
worksheet.Columns[3].AutoFit();

worksheet.get_Range("A1:A8").Copy();
}



static void CreateWordDocument()
{
var _wordApplication = new Word.Application();
_wordApplication.Visible = true;
_wordApplication.Documents.Add();
_wordApplication.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);
}
}



public class Authors
{
public dynamic Name { get; set; }
public dynamic NumberOfArticles { get; set; }
}
}

{/codecitation}

Conclusion:

In this article, we saw; how to work with office interop objects in C# 4.0. We created and opened an Excel application then displayed list of authors in the active worksheet of active Excel application. Then we opened and created a Word document, which were having an icon to link to selected area of Excel sheet. We used dynamic type for all the purpose. Download attached source code for better understanding.

Thanks for reading. Happy Coding.


About the Author


Dhananjay Kumar
Description :I done my engineering from Anand Engineering college Agra in 2007. I am MCTS WCF, MCTS MOSS Development, I am MCTS Web Development . I am native of Jamshedpur. Currently Please feel free to contact me regarding any clarification of my article at Dhananjay.25july@gmail.com

Occupation : Software Engineer
Company : UST Global.
Location : India
Follow me at twitter : http://twitter.com/dhananjay25


 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
    Today, we are talking about how to move a form without its title bar. You might have noticed that some applications with fancy UIs do not allow the user to move the window from its title bar. Honestly, some hide the overall title bar from the user. An example of these applications is Microsoft Windows Media Player -when in skin mode,- and Microsoft Windows Live Messenger. Both applications allow you to drag their windows using the client area not the title bar. In this lesson, you will lea
    Published Date : 16/Feb/2010
    This lesson focuses on how to programmatically turn on the screen saver.
    Published Date : 16/Feb/2010
    By default, arrays are stored in the managed heap with all of the overhead involved and that's because arrays simply are instances of type System.Array that inherits from System.Object. Storing an object into heap means that it will not be removed from the memory until a garbage collection (whether automatic or by calling System.GC.Collect()) occurs. Also, storing it into the heap means suffering from low-performance and the overhead (for the CLR) of storing and retrieving it into and from the h
    Published Date : 16/Feb/2010
    In addition to clearing the console screen, this lesson teaches you some about PInvoking, marshaling, and memory management. Also you will learn additional techniques like clearing a specific portion of the screen, and changing the cursor position. Moreover, you will dig into IL and see how System.Console.Clear() method do it. More than that you will learn how to reverse-engineer a .NET assembly and discover the code inside. In addition, the example shows how to perform I/O operations on cons
    Published Date : 16/Feb/2010
    Swapping mouse buttons means swapping the two buttons, making the right button acts like the left one and vice versa. This is done -for normal users of course- using the Mouse properties dialog in the control panel. See the next figure.
    Published Date : 16/Feb/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top