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

How to Integrate Excel in a Windows Form Application using the WebBrowser

By , 1 Oct 2006
 

Sample Image - Embedding_Excel.jpg

Introduction

With Automation, you are able to drive any Office application from your .NET application. This is really powerful. It may happen that one time, you would like to integrate such an application (Excel, for example) in your own application, and handle it like a control. A first approach has already been published on The Code Project (see the Background section in this article). The other method I will describe here uses the Microsoft WebBrowser control as a host for the document.

Background

You can study Anup Shinde's article. His method works fine. Instead of the WebBrowser control, it is based on Windows Win32 API.

If you are interested in the original publication of the WebBrowser method, you can see the Microsoft KB.

Starting from scratch

Create a new form MyForm, and add a new WebBrowser control, named webBrowser1. Add the m_ExcelFileName field :

// Contains the path to the workbook file
private string m_ExcelFileName="test.xls"; // Replace here with an existing file

Then create a function OpenFile like this :

public void OpenFile(string filename) 
{
    // Check the file exists
    if(!System.IO.File.Exists(filename)) throw new Exception();
        m_ExcelFileName=filename;
    // Load the workbook in the WebBrowser control
    this.webBrowser1.Navigate(filename,false);
}

You can try and run your application, giving the filename an existing excel file path. You'll see that it works perfectly. Really easy, don't you think?

In fact, you will quickly get into trouble if you try to run the application a second time with the same Excel file. An error message tells you that your file is already in use. This may be strange because you think that you closed your application, and you did. So where is the problem?

Let's see what happened in the background. While the WebBrowser was navigating, it opened an invisible Excel application, and loaded the workbook inside it. And when you closed your application, the WebBrowser didn't close either its Excel application or the workbook. So we must do it, and this is the most difficult part of our job.

Solving the problem step by step

Before further reading, you have to load the following Office COM library references for Office Automation :

  • Microsoft Excel 11.0 Object Library
  • Microsoft Office 11.0 Object Library

and use them in your file :

using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

You'll need these assemblies too :

using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;

Declare these two Excel fields :

// Contains a reference to the hosting application
private Microsoft.Office.Interop.Excel.Application m_XlApplication=null;
// Contains a reference to the active workbook
private Workbook m_Workbook=null;

Before trying to close the workbook, we need a handle on it. For convenience, the best moment to do this is just after the document has been loaded in the WebBrowser. So we have to generate a webBrowser1_Navigated event handler and its matching function, like this :

private void webBrowser1_Navigated(object sender,WebBrowserNavigatedEventArgs e) 
{
    // Creation of the workbook object
    if((m_Workbook=RetrieveWorkbook(m_ExcelFileName))==null)return;
    // Create the Excel.Application
    m_XlApplication=(Microsoft.Office.Interop.Excel.Application)m_Workbook.Application;
}

Then we define the RetrieveWorkbook function. It is based on two imported Win32 API functions, that retrieve all the programs that are running on our computer. Our job is to search among them the one that is working with the workbook that names xlfile. The code is like this :

[DllImport("ole32.dll")] static extern int GetRunningObjectTable
                (uint reserved,out IRunningObjectTable pprot);
[DllImport("ole32.dll")] static extern int CreateBindCtx(uint reserved,out IBindCtx pctx);

public Workbook RetrieveWorkbook(string xlfile) 
{
        IRunningObjectTable prot=null;
        IEnumMoniker pmonkenum=null;
        try 
        {
            IntPtr pfetched=IntPtr.Zero;
            // Query the running object table (ROT)
            if(GetRunningObjectTable(0,out prot)!=0||prot==null) return null;
            prot.EnumRunning(out pmonkenum); pmonkenum.Reset();
            IMoniker[] monikers=new IMoniker[1];
            while(pmonkenum.Next(1,monikers,pfetched)==0) 
            {
                IBindCtx pctx; string filepathname;
                CreateBindCtx(0,out pctx);
                 // Get the name of the file
                 monikers[0].GetDisplayName(pctx,null,out filepathname);
                 // Clean up
                 Marshal.ReleaseComObject(pctx);
                 // Search for the workbook
                 if(filepathname.IndexOf(xlfile)!=-1) 
                 {
                     object roval;
                     // Get a handle on the workbook
                     prot.GetObject(monikers[0],out roval);
                     return roval as Workbook;
                 }
              }
         } 
         catch 
         {
             return null;
         } 
         finally 
         {
             // Clean up
             if(prot!=null) Marshal.ReleaseComObject(prot);
             if(pmonkenum!=null) Marshal.ReleaseComObject(pmonkenum);
         }
         return null;
}

Now we can write the code involved to close the background Excel application, while overriding the OnClose() event :

protected override void OnClosed(object sender, EventArgs e) 
{
    try 
    {
        // Quit Excel and clean up.
        if(m_Workbook!=null) 
        {
            m_Workbook.Close(true,Missing.Value,Missing.Value);
            System.Runtime.InteropServices.Marshal.ReleaseComObject
                                    (m_Workbook);
            m_Workbook=null;
        }
        if(m_XlApplication!=null) 
        {
            m_XlApplication.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject
                                (m_XlApplication);
            m_XlApplication=null;
            System.GC.Collect();
        }
    } 
    catch 
    {
        MessageBox.Show("Failed to close the application");
    }
}

Using the code

You can use the code as written upper. Otherwise, it may be interesting to embed all the stuff in a .NET control. You'll be able to manage CommandBars, Menus, etc. inside the control. You will find some code in the downloadable package section.

License

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

About the Author

bsargos
Software Developer
France France
No Biography provided

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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionExcel opens outside the WebBrowser control Pinmembertieuqui905-May-13 23:58 
AnswerRe: Excel opens outside the WebBrowser control Pinmemberacesxx21-May-13 16:00 
QuestionWhen I integrate this in WPF Usercontrol the Excel Opens in new window where your example(Win forms) opening in web browsermemberMember 99615323-Apr-13 4:41 
QuestionCommand Bar not workingmemberArvind50214-Mar-13 6:15 
QuestionExcel opens directly instead of opening in Web Browser!!!!!memberMember 765864611-Feb-13 19:54 
BugExcel opens outside the WebBrowser controlmembernilesh Karekar7-Jan-13 23:33 
BugRe: Excel opens outside the WebBrowser controlmemberMirco Feliziani8-Jan-13 4:19 
GeneralRe: Excel opens outside the WebBrowser controlmemberLostMan_11-Jan-13 0:41 
GeneralRe: Excel opens outside the WebBrowser controlmemberSuperShade14-Jan-13 8:44 
QuestionHow to save the excel opened in web browser???memberAdie151123-Dec-12 17:50 
Questionhow can we implement search functionality programatically while it was loadingmemberV G S Naidu A16-Dec-12 18:41 
QuestionHow to Integrate Excel in WebForm asp.netmemberXuan Dung Phu Yen25-Aug-12 23:08 
Generalthanks a lotmemberatul don19-Jun-12 18:02 
QuestionThis article is outdated and doesn't work using IE9...memberxzz01958-Jun-12 11:15 
QuestionIn VS2008membernatmanju6-Oct-11 3:39 
QuestionDisplay excel in winform with c#memberkienhv_875-Oct-11 23:01 
AnswerRe: Display excel in winform with c#memberJayaprakash Subramanian17-Feb-12 4:25 
QuestionReading Cellsmemberakshay238629-Sep-11 2:28 
AnswerPlease note that: A new window opens when you try to view a 2007 Microsoft Office program document in Windows Internet Explorer 7 or Internet Explorer 8membersuicideas30-Jun-11 7:31 
GeneralRe: Please note that: A new window opens when you try to view a 2007 Microsoft Office program document in Windows Internet Explorer 7 or Internet Explorer 8memberbjxdylzsts19-Sep-11 1:05 
GeneralMy vote of 5membersuicideas30-Jun-11 7:26 
GeneralCommande bar not showing [modified]membermaatallah16-May-11 22:58 
GeneralRe: Commande bar not showingmembermaatallah17-May-11 23:08 
GeneralCannot see the excel in the AppsmemberLouisyu3236-Jan-11 17:37 
Questionembedding protected excel file?memberpeejay0215-Nov-10 19:57 
QuestionCommand Bar not showingmemberMember 377294928-Jul-10 2:16 
AnswerRe: Command Bar not showingmemberkyh2000b30-Mar-11 22:18 
GeneralOpens Excel 2007 in another windowmembersnorlaks25-May-10 23:24 
GeneralReference Errors Fix and "New" and "Open" bugs on Command Bar Excel Interop is dumb!!!!!memberxzz019524-Nov-09 11:18 
GeneralRe: Reference Errors Fix and "New" and "Open" bugs on Command Bar Excel Interop is dumb!!!!!memberxzz019524-Nov-09 11:31 
QuestionHow to Open blank sheet and let user create new worksheet ,open worksheet .memberlowanshi14-Oct-09 20:33 
GeneralAlternativememberFilipKrnjic14-Jul-09 2:55 
QuestionHow to add components to MenuBarmemberinisider8-Jul-09 19:53 
Generalcom object that has been separated from its underlying RCW cannot be usedmembersharma.monal22-Jan-09 23:04 
QuestionExcel sheet is opening seperatelymemberMember 472451215-Jan-09 0:46 
AnswerRe: Excel sheet is opening seperatelymemberFessen3-Sep-09 4:01 
GeneralRegarding Print Preview of Shown excell Filememberkishorekumar BV16-Dec-08 20:48 
GeneralGetActiveWorkbook(string xlfile) method returns null workbook while XMLSS file wants to openmemberPrit19742-Sep-08 1:02 
AnswerRe: GetActiveWorkbook(string xlfile) method returns null workbook while XMLSS file wants to openmemberdereklk24-Jan-10 17:23 
GeneralThe project doesnt work in VS 2008memberatef78651-Aug-08 10:45 
Generalhimembervikram12312-Jun-08 19:09 
Questionclosing word???membersalihovic2-Jun-08 22:39 
Questionafter opening an xls document and leaving the app the file is already in usemembersalihovic2-Jun-08 1:20 
AnswerRe: after opening an xls document and leaving the app the file is already in usememberRatamahatta19-Jul-08 22:56 
GeneralVS2008 and xls 2007memberPL0118-Apr-08 11:20 
GeneralRe: VS2008 and xls 2007memberasukanet28-May-08 16:15 
QuestionProblem with the Most Recently Used file of Excelmemberklew26-Feb-08 5:49 
GeneralGreat article! Thanx.memberklew15-Feb-08 6:48 
QuestionIncorrect redraw...memberAndreyVT17-Jan-08 23:50 
GeneralMicrosoft ActiveX for Embedding Office Documents in Visual Studio FormsmemberDrTom26-Sep-07 14:58 

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.130619.1 | Last Updated 1 Oct 2006
Article Copyright 2006 by bsargos
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid