Home » Azure

How to open an excel document in a webbrowser control

Hi,  I have an XBAP app that we would like to be able to open an Excel doc in a WebBrowser control but instead we always get prompted to opne in Excel.  Is this possible?  Here is what I have tried.  The reports are in SharePoint but we want to show them in our own application not SharePoint.




System.Windows.Forms.WebBrowser ReportView = new System.Windows.Forms.WebBrowser();



WindowsFormsHost ReportViewHost = newWindowsFormsHost();



"_self", postBytes, "Content-Type: application/vnd.m?s-excel");

ReportViewHost.Child = ReportView;


_filename would be something like http://localhost/shared%20documents/myfile.xslsx

Thanks for any suggestions.



5 Answers Found


Answer 1

Hi Rhonda,

It is possible to host the office application in the WPF application, please refer to the documents about Hosting a Microsoft Win32 Window in WPF: http://msdn.microsoft.com/en-us/library/ms742522.aspx#hosting_an_hwnd  and a sample provided by Dr. WPF may help you:http://drwpf.com/blog/2007/08/24/hosting-office-in-a-wpf-application/

I noticed you used a Windows.Forms.WebBrowser control and try to show the excel. Show an office document in the browser needs the ActiveX document object, please refer to this KB: http://support.microsoft.com/kb/243058. And the the problem is about how to integrate Windows Forms control in WPF, please refer to this document: http://msdn.microsoft.com/en-us/library/ms742474.aspx

(Note: if you develop a XBAP application, please use the full trust for it)


Bob Bao


Answer 2

I've actually tried all those thing and still get prompted to open in excel.




Answer 3


Thank you for your reply!

Could you please try to implement it in a desktop application first, then change it to the web application. I see it may have the aecurity problem in the web application. Did it work under the full-trust? If it is possible, could you please share some code about your application that we can help you to check?


Bob Bao


Answer 4

Here are the two functions where I am trying to load the report.  I'll play around with a console app and see if I can get it going there although ultimately this needs to run in the Outlook Task Pane browser.


private System.Windows.Forms.WebBrowser ReportViewer = new System.Windows.Forms.WebBrowser();
private WindowsFormsHost ReportViewHost = new WindowsFormsHost();

privatevoid loadReport(string rptURL)
        if ((rptUrl == "") || (rptUrl == null))
          System.Windows.MessageBox.Show("We're sorry. We could not find a report with that Id.");
          string sReport = getReportURL();
          string postStr = "";
          byte[] postBytes = Encoding.UTF8.GetBytes(postStr);

          ReportViewHost.Child = ReportViewer;

          ReportViewHost.Width = int.Parse(defaultWidth);
          ReportViewHost.MinWidth = int.Parse(defaultWidth);

          ReportViewHost.Height = 600;
          ReportViewHost.MinHeight = 600;

          ReportViewHost.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
          ReportViewHost.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
          ReportViewHost.Visibility = Visibility.Visible;
      catch (Exception ex)

privatevoid getPreferences(string listName, string reportName)
        string sReport = getReportURL(); 
        //sample report URL//sReport = "http://server/sites/subsite/Shared Documents/excelfilename.xlsx";
        _fileName = new Uri(sReport);

        BasicHttpBinding httpBinding = new BasicHttpBinding();
        httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
        httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
        httpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
        httpBinding.MaxBufferPoolSize = 2147483647;
        httpBinding.MaxReceivedMessageSize = 2147483647;
        httpBinding.MaxBufferSize = 2147483647;
        httpBinding.ReaderQuotas.MaxArrayLength = 2147483647;

        string excelServiceUrl = server + "/_vti_bin/ExcelService.asmx";

        EndpointAddress endpointAddress = new EndpointAddress(excelServiceUrl);

        this._file = new ExcelServiceSoapClient(httpBinding, endpointAddress);
        this._file.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
        _fileSessionId = _file.OpenWorkbook(_fileName.AbsoluteUri, string.Empty, string.Empty, out s);

        // _fileSessionId = _file.OpenWorkbookForEditing(_fileName.AbsoluteUri, string.Empty, string.Empty, out s);// byte[] workbook = _file.GetWorkbook(_fileSessionId, WorkbookType.FullWorkbook, out s);//// Write the resulting Excel file to stdout, as a binary stream.//BinaryWriter binaryWriter = new BinaryWriter(Console.OpenStandardOutput());//binaryWriter.Write(workbook);//binaryWriter.Close();string sCurrentParameterName = string.Empty;
        string sParameterValue = string.Empty;

        ParameterInfo[] p = new ParameterInfo[1];
        ParameterInfo param = new ParameterInfo();

        using (ClientContext clientContext = new ClientContext(server))
          Web site = clientContext.Web;
          Microsoft.SharePoint.Client.List list = clientContext.Web.Lists.GetByTitle(listName);

          CamlQuery camlQuery = new CamlQuery();
          camlQuery.ViewXml =
          @"<View><Query><Where><And><And><Eq><FieldRef Name='UserAlias'/><Value Type='Text'>" + app.User + "</Value></Eq><Eq><FieldRef Name='Title'/><Value Type='Text'>" + reportName + "</Value></Eq></And><Eq><FieldRef Name='SheetName'/><Value Type='Text'>SlicerValues</Value></Eq></And></Where></Query><RowLimit>100</RowLimit></View>";
          Microsoft.SharePoint.Client.ListItemCollection listItems = list.GetItems(camlQuery);
          if (listItems.Count > 0)
            foreach (Microsoft.SharePoint.Client.ListItem listItem in listItems)
              if (sCurrentParameterName != listItem["ParameterName"].ToString())
                if (sCurrentParameterName != string.Empty)
                  param.Name = sCurrentParameterName;
                  param.Values = a;
                  p[0] = param;
                  s = _file.SetParameters(_fileSessionId, p);

                p = new ParameterInfo[1];
                param = new ParameterInfo();
                a = new ArrayOfString();

                sCurrentParameterName = listItem["ParameterName"].ToString();
                sParameterValue = listItem["ParameterValue"].ToString();
            s = _file.CloseWorkbook(_fileSessionId);

            //here it tries to open the report in Excel instead of in the browser

            //This works but in order to open in excel services I need to use the url with the xlviewer and open the report that has the parameters set.

            //RptUrl = "http://server/_layouts/xlviewer.aspx?id=/sites/subsite/Shared Documents/excelfile.xlsx";
      catch (Exception ex)



Answer 5


I had a similar problem

Tried lots of samples that worked but with another ie window.

Try this download :







Hi all,

I am builiding a WPF application that will run inside of Outlook.  The application contains a row of buttons and a Webbrowser.  The user wants to be able to view documents from their SharePoint inside the application and use the buttons to interact with documents.  I cannot get the excel spreadsheets to open in my webbrowser.  Instead I get prompted to open in Excel.  How can I get this to work.  I am currently using:

private Microsoft.Office.Tools.Excel.Controls.WebBrowser ReportViewer = new Microsoft.Office.Tools.Excel.Controls.WebBrowser();

Uri _fileName = new Uri(sReport); 
//ReportViewer.Navigate(_fileName, "_self", postBytes, "Content-Type: application/vnd.m?s-excel");

And the URL would look like this: http://localhost/Shared Documents/myexcelsheet.xlsx  I have also tried it with a Windows.Forms.Webbrowser.

Any help would be greatly appreciated. 






How to set font size programmatically (VB or C#) in WebBrowser control or zoom WebBrowser control
After I added several mouse & keyboard events handlers in WebBrowser.OnDocumentComplete event:

            HTMLDocumentEvents2_Event eventHelper = (HTMLDocumentEvents2_Event)Document;

            eventHelper.onclick += new HTMLDocumentEvents2_onclickEventHandler(OnMouseClick);
            eventHelper.onmousedown += new HTMLDocumentEvents2_onmousedownEventHandler(OnMouseLButtonDown);

mouse wheel scrolling, as well as Document.execCommand (e.g. Document.execCommand("SelectAll", false, null)), doesn't work anymore.

Whereas mouse wheel event succesfully fired:

        private bool OnMouseWheel(IHTMLEventObj pEvtObj)
            return true; // true will cause scroll


Hello, I am making a simple application that show the X/Y coordinate of the mouse when it is over a opened PDF file into a
webBrowser control....

How can I do it?, how can get the X/Y coordenates of the mouse pointer when it is in the webroser area??, and capture it when
the user do click???

Please, any help would be very aprecciated

Thanks a lot


I am loading a PDF file from a web browser control in my WPF application, but instead of displaying the pdf document inside of my webbrowser control it is lauching Acrobat reader to display it. I want to display the pdf inside the webbrowser control. If I take the URL that I am sending to the webbrowser control and paste in internet explorer, it opens in internet explorer.

my code is doing the following

_webBrowser.Navigate(new Uri(http://infadevelopment/InfaNotesHelpFiles/Admissions.pdf));

And this opens in Acrobat instead of my webbrowser control. Any ideas how to make it open in my webbrowser control?

Thanks in advance.





I am loading a PDF file from a web browser control in my WPF application, but instead of displaying the pdf document inside of my webbrowser control it is lauching Acrobat reader to display it. I want to display the pdf inside the webbrowser control. If I take the URL that I am sending to the webbrowser control and paste in internet explorer, it opens in internet explorer.

my code is doing the following

_webBrowser.Navigate(new Uri(http://infadevelopment/InfaNotesHelpFiles/Admissions.pdf));

And this opens in Acrobat instead of my webbrowser control. Any ideas how to make it open in my webbrowser control?

Thanks in advance.

I'm using a webbrowser control and i need that when an user click on a link that could open an open/save dialog, it doesn't appear and i can download the file in background.
I tried with reading http response header to catch the file type in order to download the file but there aren't useful informations.
Any idea is appreciated.




I use the Webbrowser control (ActiveX) (http://msdn.microsoft.com/en-us/library/aa752044(VS.85).aspx) to display some banners in my application (VB).

When I click a banner then a new browser is started and the link is opened there.  This is how it should work and it  works OK for Flash-Animations and images that I click in the banner, however if I click a simple link in the banner like "http://ads.bla.bla.com"  then it opens the link inside of the WebBrowser control from my application and not in a new browser instance.

How can I make sure that a new browser is always started when I click on a banner?

thank you



First off, I am VERY new in developing add-ins and code for Office using Visual Studio, so if i need any more info please let me know.

I have a Word Add-In that displays a custom task pane with a Web Browser control, that is set to go to a sharepoint site. This site hosts a number of Office 2010 templates. The webbrowser control loads the page fine, however when a template is launched, it launches in an entirely new instance of Word 2010 and causes the initial window to stop responding.
If I enable context menus in the web browser, and right click a link to select open, it opens the template within the same instance of word and everything is fine.

I need to understand what could possibly be locking the initial instance of word, or how to intercept the link click and open a document that way.

FYI - the new window that gets loaded does not trigger any of the webbrowser events such as navigated, navigating or even document complete.

There is next to no code, this is a very simple example that has got me stumped. There is just the addition of the custom task pane.








private void button1_Click(object sender, RibbonControlEventArgs e)

UserControl1 myBMS = new UserControl1();
CustomTaskPane myBMSTaskPane = Globals.ThisAddIn.CustomTaskPanes.Add(myBMS, "Templates");
myBMSTaskPane.Width = 350;
myBMSTaskPane.Visible = true;


 Any ideas or pointers would be greatly appreciated. Thanks!



Hi , i search in google , bing , cuil and all of searchs provider for the solution of this problem :


I get HTML content from HTTPWebRequest(because is much requests and if i use WebBrowser control directly i get a lag and video processing unnecessary)


And i need  set System.Windows.Controls.WebBrowser.Document with this text.


"Solution" , use new methods call NavigateToString() or NavigateToStream()

BUT THIS PROBLEM , both DON'T work with <javascript src="something.js"> or <style src="something.css">

Navigates ONLY read and process content INSIDE this tags , no external files (like 'something.js')

Solution i encountred after two weeks of search

Process the text and replace the files by the content of that.

But this i think that is no real solution. (i tested , work , but not perfectly) * I write my own code because that post dont have source code.

for why you need to do that?

because i need interact with users after search , and use html's input to re-search again and process this file with all extern files is too slow

Any solutions?

C# Lenguage

Sorry for bad english, i'am brazilian.


I am working on a WPF application that uses System.Windows.Controls.WebBrowser to display an embedded HTML page.
The problem I have is that all links from that page that are to open an external browser window (with target="_blank") open Internet Explorer instead of the configured default browser.
How do I tell the WebBrowser control to respect the default browser settings?


Working with VB 2010 Express.. and this project is a learning tool mostly, as I have very little to no experience with any kind of programing.

I put together a form that has a ListBox, a TextBox, and a GO button.  The idea is to have a user select an item in the listbox (search engine name) type in what they are searching for.. and press go.  The code will create the proper URL and launch a browser window.  After some help from  other sources, here is what I have so far.. 

It will compile without errors, however, when I press go it tries to access the internet via port 80, but fails to open a browser window at all. 

Any help is appreciated.

Public Class Form1

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

  End Sub

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  End Sub

  Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

  End Sub

  Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Dim MyUrl As String
    Dim WebBrowser1 As New WebBrowser

    ' Lets check if the user input have some text.
    If TextBox1.Text <> "" Then

      ' If the selected listbox item is Google
      If ListBox1.SelectedItem.ToString = "Google" Then

        ' Make a string with the whole URL
        MyUrl = ("http://www.google.com/search?q=" & TextBox1.Text)

        ' Assuming you use a webbrowser control, make it navigate to the MyUrl string.

        ' Else if the selected listbox item is Yahoo
      ElseIf ListBox1.SelectedItem.ToString = "Yahoo" Then
        MyUrl = ("http://www.yahoo.com/search?q=" & TextBox1.Text)
      End If
    End If
  End Sub
End Class



When any of our Windows 7 Pro computers that run Office 2007 Pro attempt to open a Word document that resides in a WSS 2.0 document library by using the drop down menu and selecting "Edit with MS Word", the documents open in read-only.  Our work-around is to save the document locally, modify it, and then save it back to the document library.

We have some Windows XP and Vista systems that run Office 2007 and they are fine and can simply edit the document and save it.  We also have a handful of pc's that run Office 2003 and they are not having any issues either.

Things I've tried:

Office 2007 Repair - no luck Office Reinstall - no luck Some registry mod HKCU\Software\Microsoft\Office\12\Internet\OpenDocumentReadWrite=1 (noted on a MSKB article) - no luck and after re-reading the article it clearly states that this will not address content hosted on WSS or SPS sites Clearing IE temp files, resttting IE to defaults - no luck

Once again, this only seems to happen to Win7Pro pc's that run Office 2007.  Honestly, I can't tell if IE8 has anything to do with this.

Any thoughts or help would be extrememly appreciated.



Here is some of my code:


Private Sub Workbook_Open()

    Call GetQueryString

End Sub


Function GetQueryString() As Variant


strpath = ThisWorkbook.Path

If InStr(1, ThisWorkbook.FullNameURLEncoded, "?") = 0 Then

Exit Function

End If


If InStr(1, ThisWorkbook.FullNameURLEncoded, "?") > 1 Then

    strFullString = Right(ThisWorkbook.FullNameURLEncoded, Len(ThisWorkbook.FullNameURLEncoded) - InStr(1, ThisWorkbook.FullNameURLEncoded, "?"))

    strFullString = Replace(strFullString, "%20", " ", 1)


End If

If Trim(strFullString) <> "" Then

    Call AcctNo


' application close


End If

End Function


Sub AcctNo . . .


This proceeds to open another Excel file that is in SharePoint, based on a parameter that is passed to the GetQueryString function.  Somehow Excel opens TWO files, and this is totally screwing everything else up, because Excel is getting confused when two files pop open.  It seems like Excel files are being stored in cache memory.  It seems like everything is stored in cache, in C:, Documents and Settings, <myprofile>, Temporary Internet Settings, COntent.IE5, IB7MUMRR . . . I have 9 files in this folder . . . I think there should be 0 files in this folder!


Finally, I have code to close the Excel file that manages the process of opening the files that the parameter is passed to.  Here is the code to close down:


Private Sub Workbook_BeforeClose(Cancel As Boolean)

If ThisWorkbook.Name = "MainFile.xls" Then

        ThisWorkbook.Close SaveChanges:=False

End If

End Sub


This works fine if there is ONE file open named MainFile, but there are TWO files opening all the time.  I have no idea where this second Excel file is coming from, but it’s driving me crazy.  Has anyone encountered this before?  Can someone please explain what is going on?




Hi all.


I have problems with opening new windows in my new tab & new WebBrowser, and some of them i've already solved with your help (open windows with tag "_blank" in my WebBrowser). Now i have problem with opening windows with JavaScript when it's look like this:


<INPUT TYPE="button" name="" value="" title="" onclick="window.open('register.php?edit=1', '1d', 'height=500,width=800,location=yes,menubar=yes,status=yes,toolbar=yes,scrollbars=yes')">


Is there any solution? Thx!



My employer requires that and XML document be displayed upon the screen with a programable run time color scheme (backcolor, forecolor).  This works the first time I "Navigate" to the xml page.  However, if I ever "Navigate" to the page again, the color scheme does not take effect.

Each time I use the WebBrowser.Navigate("c://filename.xml") command I also set the document fore and back color.  After the first time through it always displays with a white back ground.

Any suggestions all?



I have a question that should probably have a simple answer:

I have an application that calls a method to open an existing Excel document on file. After making the changes (adding data, for example) I want the workbook to save and close. The problem is I can't get the file to open regularly, only in ReadOnly mode:

Dim xlApp AsNew Excel.Application

xlApp.Workbooks.Open(Filename:="<filename>", ReadOnly:=False)


xlApp.Visible = True
By using the code above it still opens ReadOnly. Because of this I'm unable to save the changes I make to the worksheet:
xlApp = Nothing

I have successfully used the SaveAs() method so I know the problem must be the ReadOnly

Thanks anyone for answering!

Hi everyone,

I’m trying to build an application (ASP .Net) that selects a binary file in SQL Server and open it in Word/Excel UI and when a person click in Save Button the file must be saved directly in SQL Server, like SharePoint does.

I would like to know the better way to produce this. I’ve been read these topics but I didn’t found a clear answer about this, follow links:

SharePoint Front-End Protocols

[MS-FSSHTTP]: File Synchronization via SOAP over HTTP Protocol Specification

Merging Word Documents on the Server Side with SharePoint 2010

[MS-FSSHTTPB]: Binary Requests for File Synchronization via SOAP Protocol Specification

Which is the better way?

VSTOOffice Business Application (OBA)WebDAVFrontPage Extensions

I'm using Visual Studio 2010 and SQL Server 2008 R2.
Thanks for all,



Hey All,

I'm a tech working on a bizzarre issue with OneNote. Here are some details on the environment in which I am having issues:

Windows 7 Enterprise
Office 2007 Enterprise
SharePoint 2007

When hyperlinks are put into OneNote from anywhere (typed manually, Outlook Send to OneNote Feature, copy shortcut link) they do not open. I'll click the link, it will prompt me about security (some links contain viruses, blah blah), I'll click 'Ok', and the link never opens. All of these documents are stored on SharePoint somehwere and can be accessed by taking the same link and placing it in the IE window. I've tried this with multiple documents on different SharePoint sites, all of which I have confirmed I have appropriate access to.

Its also important to note that most of the time when I click the link I get no error message - sometimes it does show the following error, but very seldom:

"Unable to open <link>. Hyperlink cannot be followed to the destination."

One workaround I have found that (sometimes works) is if I open excel first, occasionally it will open the file after clicking the link. It is inconsitent however. I also tried this on 3 separate machines of Identical hardware and image. All of them had the same issue.



I have a Excel macro which opens up other excel files through the file browser. Is it possible to open word documents this way? As i do not wan't to open a specific document..

<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure