Click here to Skip to main content
15,884,473 members
Articles / Programming Languages / C#
Article

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

Rate me:
Please Sign up or sign in to vote.
4.56/5 (26 votes)
1 Oct 2006CPOL3 min read 658K   28.4K   139   111
Another approach to integrate Office documents in your Windows C# .NET applications

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 :

C#
// 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 :

C#
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 :

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

You'll need these assemblies too :

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

Declare these two Excel fields :

C#
// 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 :

C#
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 :

C#
[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 :

C#
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)


Written By
Software Developer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAnybody got this to work with latest visual studio and loading an Excel file? I can't make it work... Pin
Motti29-Apr-20 6:32
Motti29-Apr-20 6:32 
Questionnot working Pin
Member 147638754-Mar-20 21:35
Member 147638754-Mar-20 21:35 
QuestionExcel Opens Outside the Web Browser Control Pin
Member 141286602-Jan-20 4:54
Member 141286602-Jan-20 4:54 
Questionsave changes made on the excel sheet of the UI form Pin
Member 1411450810-Jan-19 9:17
Member 1411450810-Jan-19 9:17 
QuestionWeb browser opens file a new instance of excel (and not in the browser) Pin
George Kosmidis23-Aug-18 5:38
George Kosmidis23-Aug-18 5:38 
QuestionOpen blank Excel workbook in the WebBrowser Pin
Lisa Liel24-Jul-18 10:30
Lisa Liel24-Jul-18 10:30 
QuestionEPPlus (ExcelPackage) Office OpenXML Pin
kiquenet.com16-Feb-17 2:24
professionalkiquenet.com16-Feb-17 2:24 
Questionan we generate graph from selected data of excel sheet and how Pin
Member 1279788317-Oct-16 3:24
Member 1279788317-Oct-16 3:24 
Questioncan we fetch image for this Pin
Member 1027329326-Jul-15 21:42
Member 1027329326-Jul-15 21:42 
QuestionNOT WORKING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Pin
Member 1182873310-Jul-15 7:54
Member 1182873310-Jul-15 7:54 
AnswerRe: NOT WORKING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Pin
StackThanh19-Oct-15 8:34
StackThanh19-Oct-15 8:34 
QuestionThanks working fine Pin
DilipRanjan4-May-15 10:00
DilipRanjan4-May-15 10:00 
QuestionNot Working..!! PinPopular
saratchandrakkd17-Nov-14 3:28
saratchandrakkd17-Nov-14 3:28 
AnswerRe: Not Working..!! Pin
kamija31-Aug-18 3:19
kamija31-Aug-18 3:19 
Question****** does anyone has a solution for the not visible toolbar ****** Pin
jmerum12-Nov-14 9:18
jmerum12-Nov-14 9:18 
QuestionCannot open within browser Pin
User_Beginner1-Oct-14 6:17
User_Beginner1-Oct-14 6:17 
AnswerRe: Cannot open within browser Pin
Nay Thurein Kyaw2-Oct-14 15:35
Nay Thurein Kyaw2-Oct-14 15:35 
QuestionInconvenientes al abrir aplicación. Pin
Lulopez21-Aug-14 6:16
Lulopez21-Aug-14 6:16 
GeneralMessage Closed Pin
15-Jul-14 20:40
Binu198515-Jul-14 20:40 
Questionther e is No ToolBar Pin
ahmadi_roya10-May-14 19:23
ahmadi_roya10-May-14 19:23 
Questionno toolbar Pin
fresh_girl20-Apr-14 22:35
fresh_girl20-Apr-14 22:35 
QuestionQuestion Pin
Member 817452616-Sep-13 4:39
Member 817452616-Sep-13 4:39 
At First your Application is really very good

but it opens new window to show ex cell File instead of showing it in browser control inside my form

it works well with office 2007 but it not working with 2010

any help please ,,,
QuestionWorkbook opened in web browser. But workbook assigned as null Pin
Madhavan Maddy29-Aug-13 3:10
Madhavan Maddy29-Aug-13 3:10 
QuestionExcel opens outside the WebBrowser control Pin Pin
tieuqui905-May-13 23:58
tieuqui905-May-13 23:58 
AnswerRe: Excel opens outside the WebBrowser control Pin Pin
acesxx21-May-13 16:00
acesxx21-May-13 16:00 

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.