How To: Make "Export to Excel" always open excel in a separate Window

Export to Excel in ASP.NET is a very common feature, which I'm sure everyone who has worked in ASP.NET would have had the chance to implement.
Whenever we choose the Export to Excel option from our Application, a dialog box pops us with the option to Open or to Save.

By chance if the user checks off the option "Always ask before opening this type of file" that is shown in the dialog box, from next time the user will not be able to see the dialog box. Instead, the
excel file opens up in the same window.

To set back this option, the following steps can be followed:

1. Go to Windows Explorer.
2. On the Tools menu, click Folder Options, and then click on the
File Types tab.
3. From the Registered file types list box, select the XLS extension, and then click
Advanced.
4. In the Edit File Type dialog box, set the Confirm open after download to selected.
5. Make sure the Browse in same window option is not selected, and then click
OK.

The above steps will make sure that we get the dialog box as shown above. However, since this is an option set at the client computer, these steps cannot be mandated to be followed in every computer that browses the application.

So, from the code level, we must make sure that the excel file is opened in a separate window. One possible option for this is to Save the file to the web server, and then open the file in a separate window.

In the above method, the file is saved to the Web Server inside the folder "Excel". Of course, this folder must have write permissions for the user. But it will definitely ensure that the excel file is
opened in a new window in the client computer.

Re: How To: Make "Export to Excel" always open excel in a separate Window

Excellent. Now that we're on this topic, here's a helper class that I use in regards to exporting of a DataGrid. It is updated to reflect a GridView for an application I'm upgrading, but I haven't tested it out on the GridView
yet.

Re: How To: Make "Export to Excel" always open excel in a separate Window

This looks exactly like what I'm after - but I'm a .NET/VWDE newbie and don't know where to start to implement it on my website.

I have a number of Pages with GridViews on them and would like to add an [Export to Excel] button above each one. I'd be very grateful for the steps I need to go through to do so with your code - safely assuming
that I don't have a cooking clue where to start. Here's how far I've got within VWD Express:

Add a Webform page to the site, specifying Visual C# as the Language to use.

Paste Ryan's Code between the<scriptrunat="server">and</script> at the top of the page - above the <head> tags.

Switch to Design View.

Add the Gridview to the page.

Add a Button above the Gridview.

Change the Button Text to "Export to Excel".

Double-click on the button in Design View.

Type ExportHelper

.ExportToExcelWord(I don't know what these parameters are or how to format them) between the braces.

I hope that you - or some other competent person - can help me implement this properly, by either telling me how to complete the parameters (Gridview name, HTML, ?? I suppose)
correctly, or correcting the above.

Re: How To: Make "Export to Excel" always open excel in a separate Window

The server control is taking a little longer than expected, so it's just easier to paste what I pass to the helper function. Sorry if it's a little messy. I'm in the process of revamping the app where I took the code from. Basically,
in ExportGridView you pass the GridView control, the type of file you want exported, and a file name. It should work right off the bat, but if something is messed up let me know and I'll fix it.

Re: How To: Make "Export to Excel" always open excel in a separate Window

If you use this code with a site the has an SSL certificate in IE, it wont work. You will be prompted with a msgbox 'Internet Explorer was not able to open this Internet Site. The requested site is either unavailable or cannot be found. Please try again
later'

Re: How To: Make "Export to Excel" always open excel in a separate Window

Is it better to buffer the Excel file to the file system? or to write the content straight into response stream?

Writing into the file system poses a two problems: performance and garbage.

Writing straight into stream sounds good. But I've had some annoying experience in the past: if i hit download button and choose to Open the file without any instances of Excel open, IE would have to open an instance of Excel, and then after Excel opens,
it would give an error saying something like "temporary file xxx is not found..." But if there's an existing instance of Excel when I hit the "open" button, it displays the file correctly.

Re: How To: Make "Export to Excel" always open excel in a separate Window

I tried using the example for excel, and can successfully
"save" the spreadsheet to my machine,but the "open" option fails with this error:
"... \Temporary Internet Files\content.IE5\A5GR6p25\POWERbase.xls[1].xls' could not be found.
Check the spelling... If you are trying to open the file from your list of most recently
used files on the file menu, make sur that the file has not been renamed, moved, or deleted."

Re: How To: Make "Export to Excel" always open excel in a separate Window

I tried using the example for excel, and can successfully
"save" the spreadsheet to my machine,but the "open" option fails with this error:
"... \Temporary Internet Files\content.IE5\A5GR6p25\POWERbase.xls[1].xls' could not be found.
Check the spelling... If you are trying to open the file from your list of most recently
used files on the file menu, make sur that the file has not been renamed, moved, or deleted."

Re: How To: Make "Export to Excel" always open excel in a separate Window

i have developed a web application from someone, in which there is an option "Export to Excel" and he guides me in the manual to assign inter-user rights to the Microsoft Excel Application (DCOM comopnent) from dcomcnfg.exe found within "control panel >
Admistrative tools > Components services > DCOM Configs". I have assigned the the permission to local users but still i unable to acces that particular functionality...........

i use the technique of playing with the content types............. but i am not aware of that technique

kindly help me in configuring it as well as giving me the background info of the process.... you can be technical with me

Re: How To: Make "Export to Excel" always open excel in a separate Window

Hi Ratnakar thanks for giving a short solution, but i don't know what is wrong with my aproach..i will list down my approach.. --> i have a web page with only one grid view and one button --> in button click event i have added same code what u have given,
only in place of datagrid.RenderControl(htmlWrite), i am using gridview1.RenderControl(htmlWrite); as i am having gridview with id gridview1. --> after clicking of button, i am getting this error, can you please help me out...
error is Server Error in '/rrsclient' Application. -------------------------------------------------------------------------------- Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes,
this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback
or callback data for validation. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException:
Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.
If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. Source Error: An unhandled exception was generated during the execution of the current web request.
Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ArgumentException: Invalid postback or callback argument. Event validation is enabled using in configuration or in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in
order to register the postback or callback data for validation.] System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +356 System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108 System.Web.UI.WebControls.TextBox.LoadPostData(String
postDataKey, NameValueCollection postCollection) +22 System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11 System.Web.UI.Page.ProcessPostData(NameValueCollection postData,
Boolean fBeforeLoad) +381 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2965

Re: How To: Make "Export to Excel" always open excel in a separate Window

Jamie_78

For information people.

If you use this code with a site the has an SSL certificate in IE, it wont work. You will be prompted with a msgbox 'Internet Explorer was not able to open this Internet Site. The requested site is either unavailable or cannot be found. Please try again
later'

Re: How To: Make "Export to Excel" always open excel in a separate Window

"onclick",
"window.open('./ReportInExcel.aspx?Parameter1=Value1&Parameter2=Value2')")2) Create the the same Gridview on the ReportInExcel.aspx page and add the following in the next line to the <%@Page Language=........ %> line on this page.

Re: How To: Make "Export to Excel" always open excel in a separate Window

Ok, now one of my PCs is cursed with Excel saying that it could not find the temp .xls file in the ...\temporary internet files\Content.IE5 folder and to check the spelling blah blah blah. I have looked at lots of threads with people having the same problem
and as far as I can tell nobody seems to really have an answer.

Most of the threads have source code similar to this one with some minor changes to the order of the lines of code. Some people have suggested to not use the line of code "Response.Cache.SetCacheability(HttpCacheability.NoCache);" while others seem to
be OK with it. In some threads people say the problem goes away after changing this or that but I have tried all the combinations without success on my problem PC.

Now to add my own two riduculous workarounds which my users just love to hear me suggest, I have found the following:

1) Tell users to previously open Excel on the client desktop and then run the ASP.NET code in IE and the error will be avoided. This of course isn't a real workaround since you can't expect users to do this extra step and the spreadsheet after loading does
not pop up in front of ASP.NET program which causes confusion.

2) dump Internet Explorer and use Firefox instead

To me, this problem seems like a intermittent timing issue where Excel is sometimes taking too long to open or the temp .xls file is not ready to open yet to to an issue in IE. I have made sure that my problem PC is fully updated with Microsoft patches
but that did not make any difference. Once in a while, my problem PC does not have the error on the first attempt after starting the program but then seems to always fail on the second attempt. I have run the problem PC using ASP.NET code using IIS on both
a production server and on a local IIS instance on the problem PC without any difference.

Surely, someone has a better solution to this problem. Please let me know if anyone has any fresh ideas.

Re: How To: Make "Export to Excel" always open excel in a separate Window

One of the reasons could be the size of the Excel file. There is a limit on the Excel file size if you create by exporting from ASP.NET. If you are loading too many data it may be exceeding that size limit. Try with smaller set of data just to test.

Re: How To: Make "Export to Excel" always open excel in a separate Window

The error where Excel cannot open the temp .xls file in the ...\temporary internet files\content.ie5 folder happens on small files with only a few rows as well as files with a couple of thousand rows. I also experimented with changing IE to use c:\temp\temporary
internet files instead but this didn't change anything.

It also happens on my problem PC pointing to the production server where other PCs pointing to exactly the same ASP.NET application and identical Excel files and have never had this error show up.

Re: How To: Make "Export to Excel" always open excel in a separate Window

I can run the program and let it go to the prompt where it asks to open/save/cancel the spreadsheet. At this point, I can go and look in the temp folder c:\documents and settings\myuser\local settings\temporary internet files\content.ie5 and see my output
.xls file that has been successfully created and placed in this folder. If I copy this file somewhere and open it in Excel it looks fine.

Therefore, I would assume the permissions were adequate since the file was created successfully in this folder.

Also, by the way, if I choose the "Save" option, it always works where I can download the file out of the content.ie5 folder and open the .xls file on the local drive so I guess this is a third workaround but obviously less then ideal.

Then, if I choose the "Open" option instead, and I get the error about the missing file, I see where something has erased the .xls from the c:\documents and settings\myuser\local settings\temporary internet files\content.ie5 between the point of clicking
on the Open button and the point I get the missing file error.

Once again, I am left with the theory that this is a timing thing where something is trying to clean up the file in the content.ie5 folder before Excel has a chance to grab it.

The above will work in IE7, but in IE6 if you try to "open" the file rather than save it, you will most likely get the "...xls could not be found" message in Excel because the Excel file will be deleted from the cache before Excel can open it. Remove the following
line: Response.Cache.SetCacheability(HttpCacheability.NoCache); and change the content type to the following: Response.ContentType = "application/vnd.ms-excel"; and it will work in IE6 as well as Firefox. Also make sure that you do not have caching disabled
in the OutputCache directive of your .aspx file.

Re: How To: Make "Export to Excel" always open excel in a separate Window

Thanks for your response. I tried this code it's working, i export the records into the excel and open it there is all images with data. if i paste this excel file to another system and open the excel file then there is no image found, could
you please tell me why no images will display in another machine?

Any doubts please feel free to ask me. If this post is answer of your question then don't forgot to Click "Mark As Answer".
J.Jeyaseelan

Re: How To: Make "Export to Excel" always open excel in a separate Window

I had this same problem with IE being unable to find the file and it took me a couple of hours to figure out that I had disabled DDE in excel to prevent all my excel spreadsheets from opening up in the same window. In Office 2007 click on Excel Options
then under Advanced-->General there is an "Ignore other applications that use Dynamic Data Exchange (DDE)" I had that option checked. As soon as I unchecked it, the excel opened right up on the next web call.... Now to get to the formatting.