RSS 2.0 | Atom 1.0 | CDF

Search

Categories

Archive

Blogroll

Sign In

# Wednesday, March 23, 2005
Wednesday, March 23, 2005 4:47:02 PM (GMT Standard Time, UTC+00:00) ( Asp.Net | Database )

In my web applications, i occassionaly need to allow the user to export a dataset as an excel file.  I was using a control written by Prashant Nayak posted on Code Project but he released a new version which was problematic for me, so i looked at other solutions.

obinna igbokwe  from  www.dedicatedsolutions.co.uk posted a good approach which creates a DataGrid object and binds it to the dataset, and then Renders the output of the control to the HttpResponse stream.  This works very well.  I have adapted his code to C# and added an option to specify a filename for the excel file.

Here is the code:

using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Whatever
{
 /// 
 /// This class provides a method to write a dataset to the HttpResponse as
 /// an excel file. 
 /// 
 public class ExcelExport
 {
  public static void ExportDataSetToExcel(DataSet ds, string filename)
  {
   HttpResponse response = HttpContext.Current.Response;
   
   // first let's clean up the response.object
   response.Clear();
   response.Charset = "";
   
   // set the response mime type for excel
   response.ContentType = "application/vnd.ms-excel";
   response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
   
   // create a string writer
   using (StringWriter sw = new StringWriter())
   {
    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
    {
     // instantiate a datagrid
     DataGrid dg = new DataGrid();
     dg.DataSource = ds.Tables[0];
     dg.DataBind();
     dg.RenderControl(htw);
     response.Write(sw.ToString());
     response.End(); 
    }
   }
  }
 }
}
Comments [67] | | # 
Wednesday, June 07, 2006 3:51:06 PM (GMT Daylight Time, UTC+01:00)
This works! Simple and to the point. Thanks, Tim.
Jeff
Wednesday, October 04, 2006 9:48:04 AM (GMT Daylight Time, UTC+01:00)
Do you know a method where it is possible to give the formules in the excel sheet?
Instead of just plain html text
freggel
Tuesday, April 24, 2007 10:50:04 AM (GMT Daylight Time, UTC+01:00)
This is really greate as per my requirement
Thanks Tim !!!
Ambesh
Thursday, May 17, 2007 8:05:50 PM (GMT Daylight Time, UTC+01:00)
Awesome, thanks.
Ian
Monday, January 14, 2008 9:59:51 AM (GMT Standard Time, UTC+00:00)
Thanks!!!!!!
Redzonic
Thursday, July 31, 2008 12:34:28 PM (GMT Daylight Time, UTC+01:00)
absolutly perfect code
thnx Tim
Mohd Sabir Ali
Thursday, January 29, 2009 1:31:34 PM (GMT Standard Time, UTC+00:00)
Thank you very much, clean and precise.
Ari
Sunday, May 24, 2009 1:12:11 PM (GMT Daylight Time, UTC+01:00)
I have exported grids to excel before, but I never thought about creating a method to instaniate grid just for this purpose. GREAT CONCEPT!!!!
Wednesday, June 10, 2009 10:31:52 PM (GMT Daylight Time, UTC+01:00)
How i Call this method from my UI
Please help me
Apurba Mukherjee
Wednesday, June 10, 2009 10:54:47 PM (GMT Daylight Time, UTC+01:00)
Hi
finally i solv this.Thanks for Your help.This is a great Code.
Apurba Mukherjee
Thursday, June 11, 2009 6:41:47 PM (GMT Daylight Time, UTC+01:00)
Nice post, however this is not a true Excel export, just a text stream.

Thanks
Joe Posmith
Thursday, June 11, 2009 6:43:26 PM (GMT Daylight Time, UTC+01:00)
True, but it reads perfectly in excel. In my view it's not worth trying to interop with the excel object model.
Cheers
Tim
tim
Monday, June 15, 2009 5:15:45 AM (GMT Daylight Time, UTC+01:00)
thanks for the codes. it helped me alot!! cheers!!
Alvin
Tuesday, June 23, 2009 9:04:19 PM (GMT Daylight Time, UTC+01:00)
Where can I see the exported file after I execute this code ?
musab
Tuesday, June 23, 2009 9:18:34 PM (GMT Daylight Time, UTC+01:00)
hi musab, have a read of the comment in the code " /// This class provides a method to write a dataset to the HttpResponse as
an excel file. "
once you execute the code the client can choose to open or save it, their browser may open it automatically depending on the browser settings.
if you want to write it to a file on the server, use File.WriteAllText(sw.ToString()) instead of the response.Write() parts.
good luck
tim
tim
Wednesday, June 24, 2009 5:45:23 PM (GMT Daylight Time, UTC+01:00)
I would add this to your code to help alleviate some of the strange character formatting that can result from encoding differences.

Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
Matt
Wednesday, June 24, 2009 5:48:44 PM (GMT Daylight Time, UTC+01:00)
hi Matt. thanks for the suggestion. surely your code just uses the encoding specified for the web site in web.config, or the default if not specified?
tim
Wednesday, June 24, 2009 6:24:30 PM (GMT Daylight Time, UTC+01:00)
Actually, I didn't realize there was a default setting available in the web.config. That would be a better way to deal with it, unless you needed to specify a particular encoding for your export.

Thanks for the tip!
Matt
Thursday, June 25, 2009 5:48:51 AM (GMT Daylight Time, UTC+01:00)
I see, I didn't get the response.write because I had my button inside an update panel so I thought the code doesn't work :)
But now it works great thanks alot !
Musab
Thursday, July 02, 2009 12:58:43 PM (GMT Daylight Time, UTC+01:00)
Man... Your code is so GREAT

SIMPLE UNBELIEVABLE!!!!
Well Done
Greek Nikos
Monday, August 03, 2009 8:10:06 AM (GMT Daylight Time, UTC+01:00)
Hi,

Please suggest code for windows service.
Monday, August 03, 2009 1:44:28 PM (GMT Daylight Time, UTC+01:00)
Hi,
One doubt for Excel Download. My Datatable contains value 002 whenever i download in Datatable to Excel. It shows only 2 but i need the following format 002 in Excel download file(Using ASP.Net-05, C#).Is it possible.
Help me.

Thank u.
Ganesh
Monday, August 03, 2009 4:18:14 PM (GMT Daylight Time, UTC+01:00)
Hi ganesh.
It is excel that is removing the leading zeroes from the file. If you open the file in notepad you will see they are there. For more information, google: excel leading zeroes
Tim
tim
Tuesday, August 04, 2009 10:24:14 AM (GMT Daylight Time, UTC+01:00)
Hi Tim,
Thank u for u r reply,
I want only Excel file.

Tanxs.
Ganesh
Friday, September 04, 2009 9:59:38 AM (GMT Daylight Time, UTC+01:00)
Hi Tim,

How can I generate the excel files in the client side. this code generates excel files in the server. could you help please
umit
Tuesday, September 29, 2009 10:44:05 AM (GMT Daylight Time, UTC+01:00)
hi tim,
i want to convert dataset to xls file & save file on the server.
is it possible to use your code for saving the dataset to excel file?

Thanks
Pragnesh
Pragnesh
Tuesday, September 29, 2009 10:46:13 AM (GMT Daylight Time, UTC+01:00)
Hi Pragnesh,
Instead of using Response.Write() to the web page, output the stringwriter to a file, for example:
File.WriteAllText(sw.ToString(), yourFilePath);
Good luck
Tim
tim
Thursday, October 01, 2009 9:52:30 AM (GMT Daylight Time, UTC+01:00)
hi tim,
thanks for your help.
it works great.
but i want proper excel file.
As opening of the exported file it promts it is not in proper format do you still want to open it?


Thanks
Pragnesh

Pragnesh
Wednesday, October 07, 2009 10:31:28 PM (GMT Daylight Time, UTC+01:00)
While this code works, binding a grid in code-behind to a dataset or table with 100K records is slow. This will work poorly on large sets.
Zir
Friday, November 13, 2009 3:16:16 PM (GMT Standard Time, UTC+00:00)
You saved the day! Many thanks!
Remington
Tuesday, December 15, 2009 4:06:06 PM (GMT Standard Time, UTC+00:00)
Excellent work, all working.
Thanks
Monday, December 21, 2009 3:09:44 PM (GMT Standard Time, UTC+00:00)
Hi,

I want to encode the xls file into iso-8859-1 because "é" "è" and all the other french accent doesn't show properly. I suppose I have to change the Html Header but I don't know how to do it.

Thanks
Fortin
Monday, December 21, 2009 4:43:25 PM (GMT Standard Time, UTC+00:00)
Sorry I found it:

_response.ContentEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
Fortin
Tuesday, January 05, 2010 8:53:35 AM (GMT Standard Time, UTC+00:00)
how to store large data with good performance in Excel.
Avinash
Wednesday, January 20, 2010 10:19:44 PM (GMT Standard Time, UTC+00:00)
Awesome, thanks.
Alex
Wednesday, January 27, 2010 12:49:23 PM (GMT Standard Time, UTC+00:00)
I have exported 4000 data in excel sheet but after exporting the excel sheet take very much time to open can u suggest me any solution to improve the opening time

Thanks,
Arkroop
Arkroop
Wednesday, January 27, 2010 12:52:17 PM (GMT Standard Time, UTC+00:00)
Hi arkroop,
If it takes a long time for Excel to open the file on your computer, I can't help you!
Good luck
Tim
tim
Wednesday, January 27, 2010 12:59:44 PM (GMT Standard Time, UTC+00:00)
Hi Tim,

Thanks for your responce but I have opening this excel file in different-2 pc its also taking long time to open.

Thanks
Arkroop
Wednesday, January 27, 2010 2:24:55 PM (GMT Standard Time, UTC+00:00)
hi Arkroop,
it doesn't happen for me. it may be because the file contains HTML which Excel must convert when it opens. But I often open very large files this way and I see no delays.
Tim
tim
Monday, February 08, 2010 8:25:43 AM (GMT Standard Time, UTC+00:00)
Is it possible to use this in a form instead of a website?
Monday, February 08, 2010 9:46:25 AM (GMT Standard Time, UTC+00:00)
hi mike. the output of the stringbuilder is your export text (sw.ToString()), if you are not in a web forms environment, just take the text and use it whatever way you need instead of using Response.Write etc.
good luck. tim
tim
Friday, February 26, 2010 3:21:43 PM (GMT Standard Time, UTC+00:00)
Thanks it was very usefull
Fernando
Tuesday, March 09, 2010 11:49:27 AM (GMT Standard Time, UTC+00:00)
e.Message Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack. string


Give me this error
tote
Tuesday, July 13, 2010 6:59:06 AM (GMT Daylight Time, UTC+01:00)
It is very useful and working code

Piyush
Piyush Mahajan
Wednesday, August 04, 2010 9:02:18 AM (GMT Daylight Time, UTC+01:00)
Very Good Useful Code.Helped me to export Dataset to grid. Even i did not know u can instantiate a Grid like this.
vineeta
Thursday, August 12, 2010 4:07:37 AM (GMT Daylight Time, UTC+01:00)
Hi,
Great code..i have one problem with this..whenever i run this on my local machine it will generate .xls file...but on web i.e. for my website it is not generating .xls file..not even download popup...
can u please help in this?
Thanks in advance..
Thursday, August 12, 2010 9:44:33 AM (GMT Daylight Time, UTC+01:00)
Hi,
Great code..i have one problem with this..whenever i run this on my local machine it will generate .xls file...but on web i.e. for my website it is not generating .xls file..not even download popup...
can u please help in this?
Thanks in advance..
Atul Nemade
Thursday, August 19, 2010 11:52:46 AM (GMT Daylight Time, UTC+01:00)
How can i export the tables as worksheets. One worksheet for each table in dataset is what i need.
Yuvraj
Friday, August 27, 2010 6:23:22 AM (GMT Daylight Time, UTC+01:00)
Same pbm as Yuvraj faced...Want to write multiple sheets from dataset with out using interop...
pradeep
Friday, September 03, 2010 9:57:51 PM (GMT Daylight Time, UTC+01:00)
this is really gr8
but it won't work for large amount of data where the number of rows may be more than 200K.....
biwa
Tuesday, October 26, 2010 11:19:37 AM (GMT Daylight Time, UTC+01:00)
hi,
inorder to write the sw data into an existing file i found your suggestion to use this code.
File.WriteAllText(sw.ToString(), yourFilePath);

but when i am trying to give the file path as c:\report.xsl it is saying illegal character in path .
can you suggest an option.
Thanks,
Pramuk Navap
Pramuk Navap
Thursday, November 04, 2010 9:10:54 PM (GMT Standard Time, UTC+00:00)
Thanks for the post!

To get unicode characters to display correctly in Excel, I made the following changes (vb.net):

Response.Clear()
Response.Charset = "utf-8" 'we want utf-8 for correct handling of Unicode characters in names

'set response mime type for excel
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("Content-Disposition", "attachment;filename=""" + Filename + """")

'utf8 byte order mark. From: http://blog.nicdex.com/?p=24
Dim BOM As Byte() = {&HEF, &HBB, &HBF}
Response.BinaryWrite(BOM)

'create a string writer...

davidt
Thursday, January 20, 2011 10:56:21 AM (GMT Standard Time, UTC+00:00)
This works alot but this is a class file we need to use this as a assembly.
we can refer this as a namespace,class and methods.
sai krishna
Thursday, January 20, 2011 10:58:00 AM (GMT Standard Time, UTC+00:00)
whatever.ExcelExport.ExportDataSetToExcel(ds, "c:/abc.xls");

we can call like this in your main program.. hope will work for everyone
sai krishna
Tuesday, February 15, 2011 3:49:28 PM (GMT Standard Time, UTC+00:00)
This code, unfortunately, does not work with Google Chrome nor with Firefox. When opening the XLS file the result shows the computer's background wallpaper, not the data from the dataset. How can we get around that? Thanks
maybush1
Tuesday, February 15, 2011 3:53:10 PM (GMT Standard Time, UTC+00:00)
hi maybush1, it works fine in firefox, i use it all the time. haven't tested in chrome, but there is no browser-specific content rendered, it is all generated server-side. your browser settings may be trying to embed the file in a browser window instead of prompting to download. i would suggest doing a google search on the various HTTP header options available to you when sending a file to the client. best of luck.
tim
Tuesday, April 12, 2011 4:07:08 PM (GMT Daylight Time, UTC+01:00)
Thanks Tim :) this post was very helpful and saved me a world of trouble.
Rafs
Tuesday, April 19, 2011 8:06:03 AM (GMT Daylight Time, UTC+01:00)

Thank u its really gr8
Sree
Thursday, April 28, 2011 9:51:03 AM (GMT Daylight Time, UTC+01:00)
Hi,
The code works great and it saves the data in excel but when i mail the excel file , the file that i recieve on the oter end is null without any values.

-Creator
creator
Wednesday, June 01, 2011 12:54:54 PM (GMT Daylight Time, UTC+01:00)
God bless you , it works perfectly , thank you sooooo much
AmAA
Thursday, June 30, 2011 11:06:17 AM (GMT Daylight Time, UTC+01:00)
how to export dataset tables into multiple worksheet of one workbook
pranali
Friday, July 08, 2011 7:53:17 AM (GMT Daylight Time, UTC+01:00)
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<table cellspacing="'.
Tuesday, July 19, 2011 9:43:01 PM (GMT Daylight Time, UTC+01:00)
hi,
code is simply great.but can i get the code in c#(c sharp)??
thanks,
himanshu
himanshu
Tuesday, July 19, 2011 9:56:43 PM (GMT Daylight Time, UTC+01:00)
sorry guys..
himanshu
Thursday, September 08, 2011 12:37:53 PM (GMT Daylight Time, UTC+01:00)
it is very much not good
Tuesday, November 01, 2011 6:10:44 AM (GMT Standard Time, UTC+00:00)
Superb!! It is working fine!!
Dhananjay
Friday, December 16, 2011 1:37:09 PM (GMT Standard Time, UTC+00:00)
dis code is after execution goes to catch if i use it in try{} catch{
}...
rajiv
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview