Click here to Skip to main content
Click here to Skip to main content

Silverlight 4: Interoperability with Excel using the COM Object

By , 31 May 2010
 

Table of Contents

Introduction

Silverlight 4 has the capability of accessing the COM object using the COM API. You can access any program installed in your PC using those APIs in Silverlight. You can open Notepad, Word, Excel or Outlook from a Silverlight application. Here I will demonstrate using the step-by-step tutorial on opening an Microsoft Excel book followed by data sharing between the Silverlight application and the Excel Sheet. Here, we will use a DataGrid which will load some customer information. Then we will pass the data to the Excel Sheet and then we will modify the data in the external application (i.e. inside the Excel sheet). You will see that the modified data will reflect automatically to the Silverlight Application.

See the below figure that we are going to demonstrate:

image002.png

Prerequisite

To develop this simple application, you need the following tools installed in your development environment:

  • Microsoft Visual Studio 2010
  • Silverlight 4 Tools for Visual Studio 2010

Remember that the Silverlight 4 applications can be developed only in Visual Studio 2010. Hence, if you have Visual Studio 2008 installed in your PC, you can install Visual Studio 2010 side-by-side for exploring Silverlight 4.

Getting Started

If your development environment is ready, then we can proceed towards creating a new Silverlight Application project. At the end of this part, we will be able to run our first Silverlight application inside the browser.

  1. Open your Visual Studio 2010 IDE
  2. Select File > New Project or just press CTRL + SHIFT + N to open up the New Project dialog
  3. Expand the “Visual C#” node and then go to sub node “Silverlight”
  4. Select “Silverlight Application” in the right pane
  5. Select proper location to store your application (let’s say, “D:\Sample Apps\”)
  6. Now enter a proper name for your project (call it as: “Silverlight4.Interop.Excel.Demo”)
  7. Select the .NET Framework version from the combo box at the top (I am using .NET Framework 4.0)
  8. Click OK to continue
  9. In the next dialog, make sure that “Host the Silverlight application in a new Web site” option is selected
  10. Choose “Silverlight 4” as the Silverlight Version and hit OK

Wait for a while, Visual Studio will now create the Silverlight solution for you to use which will contain a Silverlight Project and one Web Application Project to host your Silverlight application. In your Silverlight project, you will find a “MainPage.xaml” & an “App.xaml” file which are already created for you by the IDE Template.

Once you are done with setting up the project, you need to add an Assembly Reference to the Silverlight project. We will use the “dynamic” keyword, and for this we need to add the “Microsoft.CSharp” assembly reference.

  1. Right click on the “Reference” folder inside the Silverlight project and click on the “Add Reference” menu item from the context menu.

    image004.png

  2. This will open up the “Add Reference” dialog on the screen. Scroll the window to find the assembly named “Microsoft.CSharp” from the .NET tab. Select it and click “OK”. This will add the Microsoft.CSharp assembly reference into your Silverlight project. Once added, your project will support dynamic variable declaration.

    image006.png

Configuring Out-of-Browser Settings

Once you are done with setting up your Silverlight project, we are ready to implement custom Out-of-Browser Window for our application. You can read the complete article on Creating Silverlight 4 Custom Out-of-Browser window from CodeProject.

Once you design your out-of-browser Window, go to the properties of the Silverlight project. From the Silverlight pane, be sure that you are using “Silverlight 4” as target version. Now select the “Enable running application out of browser” which will make the “Out-of-Browser Settings…” button enabled. Click on it for more settings.

image008.png

From the Settings dialog window, select “Show install menu” which will create a Menu Item inside the Silverlight context menu. Once you run your application and right click on the application, you will see an “Install” menu item on it. I will come to this section later.

Now, check the “Require elevated trust when running outside the browser” as mentioned below and choose “Window Style” as “No Border”. This will make the default Chrome Window visibility to collapsed and if you run OOB, you will not see any Window border by default. Once you are done with these settings, click ok to save the configurations. You can also change the “Window Title”, “Size” and other options available there.

image010.png

Basic Design for Out-of-Browser Application

Now we will design our MainPage.xaml file with a DataGrid which will fetch Customer details from the DataProvider and generate the columns for it. We will make the DataGrid as Readonly, so that we can't directly edit the data inside it.

<sdk:DataGrid AutoGenerateColumns="True"
        Height="295"
        IsReadOnly="True"
        HorizontalAlignment="Left"
        VerticalScrollBarVisibility="Auto"
        Margin="0,30,0,0"
        x:Name="customerDataGrid"
        VerticalAlignment="Top"
        Width="576" 
        ItemsSource="{Binding CustomerCollection, 
		ElementName=userControl, Mode=TwoWay}" />

We will also set two different buttons in the Window. One for installing the application out of the browser window and the other to export the datagrid content to an Excel application. Here is the XAML code for the buttons:

<Button Height="28"
        HorizontalAlignment="Left" Click="exportToExcelButton_Click"
        Margin="244,333,0,0"
        x:Name="exportToExcelButton"
        Content="Export To Excel"
        VerticalAlignment="Top"
        Width="109" />

<Button Height="28"
        HorizontalAlignment="Left" Click="installButton_Click"
        Margin="244,333,0,0"
        x:Name="installButton"
        Content="Install"
        VerticalAlignment="Top"
        Width="109" />

Once your design is ready and you are done with data binding with your datagrid by fetching the customer information from the CustomerDataProvider, we can run the application inside the browser Window. Once loaded with fetched data, our application will look like the below figure:

image012.png

Here, you will notice the “Install” button enabled at the bottom of the DataGrid. Click the button to install this application outside the browser as a standalone application, so that, you can launch it from desktop or startmenu. When you start the installation procedure, it will pop up the Security Warning dialog. Click “Install” to continue.

image014.png

This will install the application in your local drive and automatically launch it out-of-browser. Here you will see a bit different view. You will notice that the “Install” button is no more available now and a new button named “Export to Excel” has been added to the view.

The following code block is responsible for changing the look of the application in different view:

if (App.Current.InstallState == InstallState.Installed)
{
    if (App.Current.IsRunningOutOfBrowser)
    {
        // write the code for out-of-browser window to make the
        // export to excel button visible
    }
    else
    {
        // write the code for the browser window to disable the install button
        // when the application is already installed
    }
}
else
{
    // write the code for the default view
}
image016.png

“Export to Excel” Event Implementation

  1. Let us now go for the code implementation for exporting data from the datagrid to the Excel application instance.
    First of all, we will create the instance of an Excel application and will set the visibility to true, so that, others can view it.
    excel = AutomationFactory.CreateObject("Excel.Application");
    excel.Visible = true;
  2. Now create a workbook for the instance of the opened Excel application:
    dynamic workbook = excel.workbooks;
    workbook.Add();
  3. Get the ActiveSheet from the Excel Workbook and iterate through each row and column of the datagrid collection and set the values to the Excel sheet.
    dynamic sheet = excel.ActiveSheet;
    dynamic cell = null;
    int i = 1;
     
    // iterate through the data source and populate the excel sheet
    foreach (Customer item in customerDataGrid.ItemsSource)
    {
        cell = sheet.Cells[i, 1];
        cell.Value = item.Name;
        cell.ColumnWidth = 50;
     
    
        cell = sheet.Cells[i, 2];
        cell.Value = item.ID;
     
        cell = sheet.Cells[i, 3];
        cell.Value = item.Age;
     
        i++;
    }
  4. For the first instance of the application, we will now register the SheetChange event notification to our application. This will fire the event when you modify the content of the sheet.
    if (newInstance)
    {
        App.Current.MainWindow.Closing += (MainWindow_Closing);
        excel.SheetChange += new SheetChangedDelegate(SheetChangedEventHandler);
        newInstance = false;
    }
  5. Now go for the SheetChange event implementation. Here we will get the excelSheet which we will first store as a local instance for further access to it. Then get the range of the items to update from the Excel app to our application and iterate through the items and update. Below is the code for the event implementation:
    private void SheetChangedEventHandler(dynamic excelSheet, dynamic rangeArgs)
    {
        // copy the excelsheet to a local instance for further processing
        dynamic sheet = excelSheet;
     
        // get the range of the items to update
        dynamic col2range = sheet.Range("A1:A" + CustomerCollection.Count);
     
        for (int i = 0; i < CustomerCollection.Count; i++)
        {
            // update each and every row of the datagrid with the updated column
            // the first column in our case
            CustomerCollection[i].Name = col2range.Item(i + 1).Value.ToString();
        }
    }

“Export to Excel” Demo

We are done writing the code. Now, it is time to demo it. We will now see our application to actually talk with the Microsoft Excel application. From our application, we will transfer the datagrid content to the Excel Sheet. Hence click on the “Export to Excel” button from your out-of-browser application. You will notice that one Excel sheet has been created and the data is populating in the sheet row by row.

image018.png

Let us drag our application on top of the Excel book to see the live demo. You can now see the Silverlight application on top of Excel while editing the sheet.

image020.png

Now start editing any Row of the Excel sheet. In our example, we will use the first column for editing purposes because our code checks only the first column.

// get the range of the items to update
dynamic col2range = sheet.Range("A1:A" + CustomerCollection.Count);
image022.png

Once you are done modifying the cell of the Excel sheet, just press Enter, so that it will come out from the edit mode. Hey what happened? Did you notice anything in our application? Yes right, in our application, the corresponding cell got updated with the modified cell content.

image024.png

What Next?

I think you now got the idea of Silverlight - Excel messaging through the COM API. This was a small demonstration of the new feature. You can now modify it for a bigger range of cell to update the Silverlight datagrid from Excel sheet. Be sure that it will only work for Silverlight trusted Out-of-Browser applications.

Please vote for this article and let me know if you have any feedback or suggestions, so that I can improve it for you.

History

  • Initial post (28-May-2010)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

_ Kunal Chowdhury _
Software Developer
India India
Member
Kunal Chowdhury is a Microsoft MVP (Most Valuable Professional) in Silverlight Technology, a Codeproject MVP & Mentor, DZone MVB (Most Valuable Blogger), Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.
 
He is currently working as a Software Engineer II in an MNC located at Pune, India. He has a very good skill over XAML, C#, Silverlight and WPF. He has a good working experience in Windows 7 application (including Multi-touch) development too.
 
He posts his findings in his technical blog. He also writes for SilverlightShow and Codeproject portal. Many of his articles were highlighted as "Article of the Day" in Microsoft sites.
 
He also has another website called Silverlight-Zone.com where he posts article links on Silverlight, Windows Phone 7 and XNA accumulated from various web sites to help the community grow on specified technologies.
 
You can reach him in his Blog : http://www.kunal-chowdhury.com
He is also available in Twitter : http://twitter.com/kunal2383

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionCan be SL 4 used to host MS Office apps in html?memberR_PR3 Jun '10 - 5:21 
Good article!
 
And now the question: can be SL 4 used to host MS Office apps (e.g. Word) in HTML page to replace well-known DSOFramer?
 
Can Word be embedded in User Control on HTML page? Confused | :confused:
AnswerRe: Can be SL 4 used to host MS Office apps in html?memberDewey3 Jun '10 - 12:31 
The short answer is YES!
 
You have full control over the browser in SL 4, OOB.
 
Just use the browser control, and you may embed it into any portion of your silverlight app.
GeneralRe: Can be SL 4 used to host MS Office apps in html?memberR_PR3 Jun '10 - 22:40 
Can you expand your thought a little bit?
I need to embed MS Office apps in HTML page. I undestood that I can run them from HTML through OOB. It will be the separate window with Excel (e.g.) running. How I can have this Excel shown and working inside my HTML page?
GeneralVery usefullmemberdefwebserver31 May '10 - 14:09 
Somewhere there is some programmer who is being asked by their boss "hey so I want the program to talk to Excel", and that programmer is thanking you right now...
GeneralRe: Very usefullmentorKunalChowdhury31 May '10 - 16:16 
Thanks a lot Michael for such a nice feedback. Please don't forget to vote. Smile | :)
Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralNice, & if it gets Sacha going - I love it!!!memberAlan Beasley30 May '10 - 22:43 
Hi Kunal,
 
Nice to see yet another article, as well as paying attention to making the screen shots look nice.
However I was left wondering: Why?
I'm not saying it is a bad idea, just that at first glance I thought the article may have something to do with cutting the corners off. But I'm easily confused!!! Big Grin | :-D
 
Anyway thanks for showing how Silverlight can interface with Office applications! 5 Stars! Thumbs Up | :thumbsup:

If I could code, I'd be dangerous... My Blog[^]

GeneralRe: Nice, & if it gets Sacha going - I love it!!!mentorKunalChowdhury31 May '10 - 7:17 
Hi Alan,
 
Alan Beasley wrote:
Nice to see yet another article, as well as paying attention to making the screen shots look nice.

 
Thanks for your feedback. I am happy that you liked the Article as well as the representation of the screenshots. Shucks | :-> Also sorry for confusing you a little bit by putting the screenshots with the new corners. Hmmm... I think that gave you more interest to the article to read. Am I right? Laugh | :laugh:
 

Alan Beasley wrote:
Anyway thanks for showing how Silverlight can interface with Office applications! 5 Stars!

 
Thanks again. Also, some more to come. Keep an eye.
Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralRe: Nice, & if it gets Sacha going - I love it!!!memberAlan Beasley31 May '10 - 8:28 
LOL, OK I've picked myself off the floor & stopped laughing. - You are under the illusion that I can code! Laugh | :laugh: Or even want to code!! Laugh | :laugh: Laugh | :laugh:
 
I'm not kidding, the only time I want to see VS, is on someone else's screen! Laugh | :laugh:
The UI is the only thing I care about & hooking into the code in point & click mode... The rest is your playground....
 
So I scanned, logged & referred someone to it on the SL forum today! But read it? Oh I could die... Laugh | :laugh: (However I would read it, if it became relevent to me!)
 
But if I can't do it in blend alone, then I don't actually want to know. As otherwise designers become developers? & you coders unemployed...

If I could code, I'd be dangerous... My Blog[^]

GeneralRe: Nice, & if it gets Sacha going - I love it!!!mentorKunalChowdhury31 May '10 - 16:18 
ha ha ha... Laugh | :laugh: Again, thanks for sharing the link.
Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralBroken LinkmemberDewey30 May '10 - 22:15 
The source code is missing.
 
BTW, I do think this will be possible on the Mac in the future.
AnswerRe: Broken LinkmentorKunalChowdhury31 May '10 - 6:58 
Dewey wrote:
The source code is missing.

 
Hi Dewey,
 
Thanks for bringing that to my notice. I updated it with a new link. Please try it and let me know if you have any issue.
 

Dewey wrote:
BTW, I do think this will be possible on the Mac in the future.

 
Not sure, though COM is not supported in MAC (I guess) but some other way Microsoft can think of about it for future releases. Nothing is impossible by them. Laugh | :laugh:
Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralRe: Broken LinkmemberDewey2 Jun '10 - 10:30 
Thanks, the link is fixed.
 
COM is not supported on the Mac, however, AppleScript does essentially the same thing, and MS has hinted that they may do an AppleScript interface.
 
Once that is done, using the Mac in the same way we do on Windows would make them more equal. Unfortunately that still would leave Linux out of the picture.
 
So many OS's so little time...
GeneralRe: Broken LinkmentorKunalChowdhury2 Jun '10 - 18:24 
Thanks for sharing the information about MAC & Linux.
Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralGood article, but I personally think COM and SL are insane ideasmvpSacha Barber28 May '10 - 22:26 
For me SL should do web stuff and if you find your are needing to use EXCEL from a web page, jesus, man that screams of using WPF or Winforms or some desktop app technology. I am not having a go at you here at all, you are just demoing how to do it, which is cool, and you did a god job on that.
 
It is just I think, watching SL doing all this, will lead people to make bad technology choices, I do not understand why people can not see that technology should be used for its strengths and not try and get it to do everything even if it should not.
 
Anyway this article is cool, and does what you say it does, so have a 5.
 
PS: Have a look at this for more crazed SL stuff (I don't like it doing this, but it can, should it, mmm moral choice there).
 
http://justinangel.net/#BlogPost=CuttingEdgeSilverlight4ComFeatures[^]
Sacha Barber
  • Microsoft Visual C# MVP 2008-2010
  • Codeproject MVP 2008-2010
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Good article, but I personally think COM and SL are insane ideasmentorKunalChowdhury28 May '10 - 22:57 
Thanks Sacha for your feedback. Yes, in Silverlight it is not as useful but as the technology is changing and moving to out-of-browser, hence it may help in some business scenarios. BTW, this is just a demonstration of the interoperability and you voted for that. Thanks again.
Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralRe: Good article, but I personally think COM and SL are insane ideasmvpDaniel Vaughan29 May '10 - 3:45 
When I got my first glimpse of Linq, I thought to myself “Oh no, our C# language is being polluted with some hodgepodge SQL like syntax!” Obviously I’ve since come around to see how great it is.
Likewise, Silverlight may appear on the surface to be purely a web technology. But remember, now we have OOB and WP7. For sure, WPF is a richer technology to work with in many ways, and I still prefer it. But in my view Silverlight is ‘the’ cross platform technology. I have a client who is targeting the web, desktop, and Windows Phone with the same codebase, and it simplifies things a lot having COM interop available for the OOB implementation.
 
Kunal, very good article. Got my 5. Well done. Smile | :)
 
Cheers,
Daniel
Daniel Vaughan
Twitter | Blog | Microsoft MVP | Projects: Calcium SDK, Clog | LinkedIn

GeneralRe: Good article, but I personally think COM and SL are insane ideasmvpSacha Barber29 May '10 - 6:29 
This is just because you are writing a WP7 book is it Mr Vaughan. Cheeky monkey.
Sacha Barber
  • Microsoft Visual C# MVP 2008-2010
  • Codeproject MVP 2008-2010
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Good article, but I personally think COM and SL are insane ideasmvpDaniel Vaughan29 May '10 - 19:22 
Not at all! Wink | ;)
Daniel Vaughan
Twitter | Blog | Microsoft MVP | Projects: Calcium SDK, Clog | LinkedIn

GeneralRe: Good article, but I personally think COM and SL are insane ideasmvpSacha Barber29 May '10 - 20:50 
PST : When you say "Silverlight is ‘the’ cross platform technology", fair enough, though OOB and COM, really? Cross platform? I don'y know enough about macs, I know you can get office, but is it still COM based? I don't know sounds weird though. Do macs even have the same concepts for COM?
 
PS: Just read "going down the COM interop route makes your application Windows only" on Mike Taulty blog, so there we have it. COM = no cross platform.
Sacha Barber
  • Microsoft Visual C# MVP 2008-2010
  • Codeproject MVP 2008-2010
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Good article, but I personally think COM and SL are insane ideasmvpDaniel Vaughan29 May '10 - 21:29 
Yes, but it's there if you need it for Windows. What I have in mind is a particular scenario: A large codebase with client variants for desktop, web browser, and WP7 (with each differing in some functionality). By having COM it means SL can be used to target the desktop variant (which may happen to need some extra capabilities); using COM interop for say some thrid party APIs, and without having to build a seperate WPF client for that. In terms of code reuse, it simplifies things a lot.
Daniel Vaughan
Twitter | Blog | Microsoft MVP | Projects: Calcium SDK, Clog | LinkedIn

GeneralRe: Good article, but I personally think COM and SL are insane ideasmentorKunalChowdhury29 May '10 - 21:56 
Daniel Vaughan wrote:
using COM interop for say some thrid party APIs, and without having to build a seperate WPF client for that. In terms of code reuse, it simplifies things a lot.

 
I am strongly agree on this, because it is targeting all the three platforms. Thumbs Up | :thumbsup:
Don't forget to Click on [Vote] and [Good Answer] on the posts that helped you.


Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets | Silverlight Tutorial

GeneralRe: Good article, but I personally think COM and SL are insane ideasmvpSacha Barber29 May '10 - 22:12 
I know I know, I just like sticking the knife in SLs ugly side is all. Poke tongue | ;-P
Sacha Barber
  • Microsoft Visual C# MVP 2008-2010
  • Codeproject MVP 2008-2010
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

JokeRe: Good article, but I personally think COM and SL are insane ideasmemberAlan Beasley30 May '10 - 22:32 
Ah Mr Barbarella, we meet again... (Stroking cat)
 
And once again you're giving Silverlight a hard time! Hmmm | :|
 
What is it they say about a workman & his tools? Poke tongue | ;-P
 
Sacha Barber wrote:
I just like sticking the knife in SLs ugly side

And I just want to stick the knife in your ugly side, but that would require my whole cutlery set!!! Laugh | :laugh:
 
Go Daniel, Go Daniel, Go Daniel!!!

If I could code, I'd be dangerous... My Blog[^]

GeneralRe: Good article, but I personally think COM and SL are insane ideasmvpSacha Barber30 May '10 - 23:26 
Ill cut your fecking head off chump. I used to be known as Dr Machette (when I was making hardcore punk tehcno you know, check it out http://www.discogs.com/artist/Dr.+Machette[^] and also my band Uk Skullf**k http://www.discogs.com/search?q=uk+skullfuck&type=all&btn=Search[^] and my own record label Surgeon 16 http://www.discogs.com/label/Surgeon+16+Recordings[^])
Sacha Barber
  • Microsoft Visual C# MVP 2008-2010
  • Codeproject MVP 2008-2010
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Good article, but I personally think COM and SL are insane ideasmemberAlan Beasley30 May '10 - 23:47 
LOL - Yeah Yeah I'm quaking in my boots stumpy!!! (You look short!) Poke tongue | ;-P
 
All I can say about your musical taste & ability is: Lucky you can code!!! Big Grin | :-D
 
I'll put you in a "Drowning Pool" & "Let The Bodies Hit The Floor!!!"
 
I'd love to hear you "Korn" on, while you "Rage Against the Machine" & I've a "Five Finger Death Punch" for you!!! Poke tongue | ;-P
 
P.S. I used to be called the Grim Reaper!!! So there... (But that was in a darts team...) Laugh | :laugh:

If I could code, I'd be dangerous... My Blog[^]

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 31 May 2010
Article Copyright 2010 by _ Kunal Chowdhury _
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid