Click here to Skip to main content
11,920,641 members (60,876 online)
Click here to Skip to main content
Add your own
alternative version


130 bookmarked

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

, 1 Oct 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
Another approach to integrate Office documents in your Windows C# .NET applications

Sample Image - Embedding_Excel.jpg


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.


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();
    // Load the workbook in the WebBrowser control

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
    // Create the Excel.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;
            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];
                IBindCtx pctx; string filepathname;
                CreateBindCtx(0,out pctx);
                 // Get the name of the file
                 monikers[0].GetDisplayName(pctx,null,out filepathname);
                 // Clean up
                 // Search for the workbook
                     object roval;
                     // Get a handle on the workbook
                     prot.GetObject(monikers[0],out roval);
                     return roval as Workbook;
             return null;
             // 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) 
        // Quit Excel and clean up.
        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.


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


About the Author

Software Developer
France France
No Biography provided

You may also be interested in...

Comments and Discussions

Questioncan we fetch image for this Pin
Member 1027329326-Jul-15 22:42
memberMember 1027329326-Jul-15 22:42 
QuestionNOT WORKING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Pin
Member 1182873310-Jul-15 8:54
memberMember 1182873310-Jul-15 8:54 
AnswerRe: NOT WORKING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Pin
StackThanh19-Oct-15 9:34
memberStackThanh19-Oct-15 9:34 
QuestionThanks working fine Pin
DilipRanjan4-May-15 11:00
memberDilipRanjan4-May-15 11:00 
QuestionNot Working..!! Pin
saratchandrakkd17-Nov-14 4:28
membersaratchandrakkd17-Nov-14 4:28 
Question****** does anyone has a solution for the not visible toolbar ****** Pin
multitasker12-Nov-14 10:18
membermultitasker12-Nov-14 10:18 
QuestionCannot open within browser Pin
User_Beginner1-Oct-14 7:17
memberUser_Beginner1-Oct-14 7:17 
AnswerRe: Cannot open within browser Pin
Nay Thurein Kyaw2-Oct-14 16:35
memberNay Thurein Kyaw2-Oct-14 16:35 
QuestionInconvenientes al abrir aplicación. Pin
Lulopez21-Aug-14 7:16
memberLulopez21-Aug-14 7:16 
GeneralNice one Pin
Binu198515-Jul-14 21:40
memberBinu198515-Jul-14 21:40 
Questionther e is No ToolBar Pin
ahmadi_roya10-May-14 20:23
memberahmadi_roya10-May-14 20:23 
Questionno toolbar Pin
fresh_girl20-Apr-14 23:35
memberfresh_girl20-Apr-14 23:35 
QuestionQuestion Pin
Member 817452616-Sep-13 5:39
memberMember 817452616-Sep-13 5:39 
QuestionWorkbook opened in web browser. But workbook assigned as null Pin
Madhavan Maddy29-Aug-13 4:10
memberMadhavan Maddy29-Aug-13 4:10 
QuestionExcel opens outside the WebBrowser control Pin Pin
tieuqui906-May-13 0:58
membertieuqui906-May-13 0:58 
AnswerRe: Excel opens outside the WebBrowser control Pin Pin
acesxx21-May-13 17:00
memberacesxx21-May-13 17:00 
GeneralRe: Excel opens outside the WebBrowser control Pin Pin
SabrinaY8-Aug-13 18:42
professionalSabrinaY8-Aug-13 18:42 
It works well! Thank you so much! Poke tongue | ;-P
AnswerRe: Excel opens outside the WebBrowser control Pin Pin
Member 817452618-Sep-13 0:50
memberMember 817452618-Sep-13 0:50 
QuestionWhen I integrate this in WPF Usercontrol the Excel Opens in new window where your example(Win forms) opening in web browser Pin
Member 99615323-Apr-13 5:41
memberMember 99615323-Apr-13 5:41 
AnswerRe: When I integrate this in WPF Usercontrol the Excel Opens in new window where your example(Win forms) opening in web browser Pin
SabrinaY15-Aug-13 22:43
professionalSabrinaY15-Aug-13 22:43 
QuestionCommand Bar not working Pin
Arvind50214-Mar-13 7:15
memberArvind50214-Mar-13 7:15 
QuestionExcel opens directly instead of opening in Web Browser!!!!! Pin
Member 765864611-Feb-13 20:54
memberMember 765864611-Feb-13 20:54 
BugExcel opens outside the WebBrowser control Pin
nilesh Karekar8-Jan-13 0:33
membernilesh Karekar8-Jan-13 0:33 
BugRe: Excel opens outside the WebBrowser control Pin
Mirco Feliziani8-Jan-13 5:19
memberMirco Feliziani8-Jan-13 5:19 
GeneralRe: Excel opens outside the WebBrowser control Pin
LostMan_11-Jan-13 1:41
memberLostMan_11-Jan-13 1:41 
GeneralRe: Excel opens outside the WebBrowser control Pin
SuperShade14-Jan-13 9:44
memberSuperShade14-Jan-13 9:44 
QuestionHow to save the excel opened in web browser??? Pin
Adie151123-Dec-12 18:50
memberAdie151123-Dec-12 18:50 
Questionhow can we implement search functionality programatically while it was loading Pin
V G S Naidu A16-Dec-12 19:41
memberV G S Naidu A16-Dec-12 19:41 
QuestionHow to Integrate Excel in WebForm Pin
Xuan Dung Phu Yen26-Aug-12 0:08
memberXuan Dung Phu Yen26-Aug-12 0:08 
Generalthanks a lot Pin
atul don19-Jun-12 19:02
memberatul don19-Jun-12 19:02 
QuestionThis article is outdated and doesn't work using IE9... Pin
xzz01958-Jun-12 12:15
memberxzz01958-Jun-12 12:15 
QuestionIn VS2008 Pin
natmanju6-Oct-11 4:39
membernatmanju6-Oct-11 4:39 
QuestionDisplay excel in winform with c# Pin
kienhv_876-Oct-11 0:01
memberkienhv_876-Oct-11 0:01 
AnswerRe: Display excel in winform with c# Pin
Jayaprakash Subramanian17-Feb-12 5:25
memberJayaprakash Subramanian17-Feb-12 5:25 
QuestionReading Cells Pin
akshay238629-Sep-11 3:28
memberakshay238629-Sep-11 3: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 8 Pin
suicideas30-Jun-11 8:31
membersuicideas30-Jun-11 8: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 8 Pin
bjxdylzsts19-Sep-11 2:05
memberbjxdylzsts19-Sep-11 2:05 
GeneralMy vote of 5 Pin
suicideas30-Jun-11 8:26
membersuicideas30-Jun-11 8:26 
GeneralCommande bar not showing [modified] Pin
maatallah16-May-11 23:58
membermaatallah16-May-11 23:58 
GeneralRe: Commande bar not showing Pin
maatallah18-May-11 0:08
membermaatallah18-May-11 0:08 
GeneralCannot see the excel in the Apps Pin
Louisyu3236-Jan-11 18:37
memberLouisyu3236-Jan-11 18:37 
Questionembedding protected excel file? Pin
peejay0215-Nov-10 20:57
memberpeejay0215-Nov-10 20:57 
QuestionCommand Bar not showing Pin
Member 377294928-Jul-10 3:16
memberMember 377294928-Jul-10 3:16 
AnswerRe: Command Bar not showing Pin
kyh2000b30-Mar-11 23:18
memberkyh2000b30-Mar-11 23:18 
GeneralOpens Excel 2007 in another window Pin
snorlaks26-May-10 0:24
membersnorlaks26-May-10 0:24 
GeneralRe: Opens Excel 2007 in another window Pin
SabrinaY8-Aug-13 18:38
professionalSabrinaY8-Aug-13 18:38 
GeneralReference Errors Fix and "New" and "Open" bugs on Command Bar Excel Interop is dumb!!!!! Pin
xzz019524-Nov-09 12:18
memberxzz019524-Nov-09 12:18 
GeneralRe: Reference Errors Fix and "New" and "Open" bugs on Command Bar Excel Interop is dumb!!!!! Pin
xzz019524-Nov-09 12:31
memberxzz019524-Nov-09 12:31 
QuestionHow to Open blank sheet and let user create new worksheet ,open worksheet . Pin
lowanshi14-Oct-09 21:33
memberlowanshi14-Oct-09 21:33 
GeneralAlternative Pin
FilipKrnjic14-Jul-09 3:55
memberFilipKrnjic14-Jul-09 3:55 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151120.1 | Last Updated 1 Oct 2006
Article Copyright 2006 by bsargos
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid