Sections
     
     
WWWCoder.com Resource Directory

Exporting Data Grid to Excel
6/13/2005 1:32:35 PM

The datagrid is one of the most coolest controls in the Asp.net. One thing that all developers need is to put the data grid data into Excel sheet. In this article I will show you that how you can export your datagrid data to Excel file, Word file and also Text file.

Exporting datagrid to Excel:

Exporting datagrid to excel might sounds complex but its pretty simple. Let's see how this can be done.

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

The code given above is the complete code to export the datagrid to excel file.

  • Response.AddHeader is letting Asp.net know that we are exporting a file which is named FileName.xls
  • Response.ContentType denotes the type of the file being exported
  • myDataGrid.RenderControl(htmlWrite) which writes the data to the HtmlTextWriter
  • Response.Write(stringWrite.ToString()); which send the request to the response stream.

As you can see exporting the datagrid to excel is pretty simple.

Exporting the datagrid to word file:

You can also export the datagrid to the word file. You might ask a question that why would anyone like to do that. If you have a word document which needs table than you can simple export the table from the datagrid to the word document. The code is similar to the above with little minor changes.

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

 

  • The only changes we made is in bold. 
    • Exporting the datagrid to a Text File:

      Sometimes you need to export the whole datagrid to a text file. In this case you need to iterate through the dataset and concatenate the text to string or more precisely StringBuilder object. Let's see how this can be done.

      Database db = DatabaseFactory.CreateDatabase();
      DBCommandWrapper selectCommandWrapper = db.GetStoredProcCommandWrapper("sp_GetLatestArticles");
      DataSet ds = db.ExecuteDataSet(selectCommandWrapper);
      StringBuilder str = new StringBuilder();
      for
      (int i=0;i<=ds.Tables[0].Rows.Count - 1; i++)
      {
      for
      (int j=0;j<=ds.Tables[0].Columns.Count - 1; j++)
      {
      str.Append(ds.Tables[0].Rows[i][j].ToString());
      }
      str.Append("<BR>");
      }
      Response.Clear();
      Response.AddHeader("content-disposition", "attachment;filename=FileName.txt");
      Response.Charset = "";
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.ContentType = "application/vnd.text";
      System.IO.StringWriter stringWrite = new System.IO.StringWriter();
      System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
      Response.Write(str.ToString());
      Response.End();

      The important thing to note is the two for loops that iterates through the dataset and append the rows into the StringBuilder object.

      I would like to thank Sonu Kapoor for helping me with the Format issue in Exporting DataGrid to Excel and Juss for providing the code.

      Format Issue when Exporting datagrid to Excel:

      When you export the datagrid to Excel it looses it format. It means that maybe your datagrid has string field which consisted of numbers say '002345'. But when you export the grid and see it in excel file you will find that the number changed to '2345'.

      You can solve this problem using Cascading Style Sheets.

      Code provided by Juss:

      Dim strFileName, strFilePath As String
      Dim
      oStringWriter As New System.IO.StringWriter
      Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
      Dim objStreamWriter As StreamWriter
      Dim strStyle As String = "<style>.text { mso-number-format:\@; } </style>"
      objStreamWriter = File.AppendText(strFilePath)
      DataGrid1.RenderControl(oHtmlTextWriter)
      objStreamWriter.WriteLine(strStyle)
      objStreamWriter.WriteLine(oStringWriter.ToString())
      objStreamWriter.Close()

      Most of you might be thinking that what is that mso-number-format stuff in between the code. This is the style in which the column will be exported. For this reason you need to inject the attribute into the datagrid column for which you want to change the display format.

      DataGrid1.DataBind()
      Dim strStyle As String = "<style>.text { mso-number-format:\@; } </style>"
      For intTemp As Integer = 1 To ds.Tables(0).Rows.Count - 1
         DataGrid1.Items(intTemp).Cells(0).Attributes.Add("class", "text")
      Next

      You can export in many formats. All you need to know is the mso-number-format:\@; . You can easily find the format by going opening excel file and typing the number in one of the cells. Now if you want to save this number as a Social Security Pattern (xxx-xx-xxxx), right click on the cell and select a pattern that saves it as a Social Security Number. Next save the Excel file to xml format. Open the xml file in notepad and see that column SSN uses what style. The SSN style is something like this: mso-number-format:000\-00\-0000.

      Simply substitute the new style in the strStyle variable and that's it.

      For the complete discussion on this issue please visit the following like:

      http://forums.asp.net/ShowPost.aspx?PageIndex=2&PostID=893621#893621

      I hope you liked the article, happy coding !

      download code files

      About the Author:

      My name is Mohammad Azam. You might know me as "AzamSharp". I started programming at the age of 13 with GW BASIC as my first programming language. Later I switched to C programming language and now I exclusively develop solutions in C#.

      I have written several articles for many websites. Some of them are also published on Microsoft Official Website www.asp.net. You will find most of my articles on www.codersource.net

       I spend most my time reading .net articles and posting solutions to questions on asp.net forums. I am also Top 25 poster on Asp.net forums. Currently I am an undergraduate student in University of Houston. I will be graduating in Fall 2005. I am also working as an Asp.net developer for my university.

      My hobbies include listening music, playing video games and walk on a sunny day. Recently I got engaged to the most beautiful girl in the world which is the best thing ever happened to me. I would also like to thank my parents for all their support and love they have given me on every step of life.

      You can contact me at azamsharp@gmail.com.

       


      Page Options:
      format for printing  Format for Printer
      email article  Email Page
      add to your favorites   Add to Favorites
      How would you rate the quality of this content?
      Poor - - Excellent
      Comments?
      Overall Rating:
      Comments Left:
      Left on 8/26/2009 9:26:38 AM by Anonymous
      Comments: i didnt find the answer for my question - how to export datagrid into pdf format ???
      No ratings available.
      Left on 7/20/2009 4:24:50 AM by Anonymous
      Comments: Don't work with Excel 2007, file extension dialog box pops up
      Left on 6/29/2009 7:25:09 AM by Anonymous
      Comments: This code doesn't work if some one is using excel 2007
      No ratings available.
      Left on 4/7/2009 12:34:01 AM by Anonymous
      Comments: gooooood
      Left on 3/20/2009 10:56:16 AM by Anonymous
      Comments: ovviamente non funziona!!!
      Left on 11/9/2008 4:29:09 AM by Anonymous
      Comments: not use c# code .only in vb code
      No ratings available.
      Left on 6/30/2008 7:38:57 AM by Anonymous
      Comments: what is response for???
      Left on 6/11/2008 1:19:56 AM by Anonymous
      Comments: ll
      Left on 3/18/2008 5:08:55 PM by Anonymous
      Comments: i got a problem whit the response sentence. vb cant take it.
      No ratings available.
      Left on 12/27/2007 1:08:06 AM by Anonymous
      Comments: but how to transfer date to multi sheets on excel
      Left on 9/16/2007 11:47:54 PM by Anonymous
      Comments: i didnt find my wuestion answer my question is how to convert datagrid table into pdf format

      Left on 9/16/2007 11:45:23 AM by Anonymous
      Comments: It export data from all columns. I just want to export data from two columns. Can u help me.
      No ratings available.
      Left on 8/15/2007 4:55:15 AM by Anonymous
      Comments: Not working when I deploy to a production server.
      Left on 5/30/2007 7:29:17 AM by Anonymous
      Comments: I M Very thankfull to this site that provide me this code
      Left on 5/9/2007 5:55:41 AM by Anonymous
      Comments: I am facing this problem. "Sys.WebForms.PageRequestManagerParseEErrorException:The message received from the server could not be parsed.Common cause for this error are when th response is modified by calls to Response.Write(),response filters, HTTP Modues or server trace is enabled. Details:Error parsing near'<Table>'". Please help me out
      No ratings available.
      Left on 5/9/2007 5:53:56 AM by Anonymous
      Comments: Good article but problem i am facing is this that "Sys.WebForms.PageRequestManagerParseEErrorException:The message received from the server could not be parsed.Common cause for this error are when th response is modified by calls to Response.Write(),response filters, HTTP Modues or server trace is enabled. Details:Error parsing near'<Table>'"
      Left on 3/8/2007 8:28:14 AM by Anonymous
      Comments: When the datagrid viewstate is set to false the export to excel doesn't work.
      Left on 3/1/2007 1:33:35 PM by Anonymous
      Comments: Looks like a great article covering all the bases.  I haven't tried it yet, but the no-cache option worries me.  I had that set once, and I could "open" the file in the browser, but when I tried to save to a file, I got an annoying error that the web page was not available.  Because of no-cache, the file was being deleted before it could be copied!  Something to watch out for, that's all...
      No ratings available.
      Left on 2/3/2007 4:24:32 AM by Anonymous
      Comments:
      Left on 1/23/2007 1:11:13 PM by Anonymous
      Comments: When I deploy my web app to our portal server, the excel file does not open. Seems to me like a security isue. It works fine from my localhost.
      Left on 1/10/2007 11:58:28 AM by Anonymous
      Comments: i have added columns on code, and it don't appear when i export to excel.. how can i do to this dinamic collumns appear? thanks
      Left on 12/11/2006 2:44:02 PM by Anonymous
      Comments: Can you tell how to disable the open button.

      Left on 11/27/2006 4:48:38 AM by Anonymous
      Comments: its interesting but can u pls tell the code how we could wrie data from one form to excel in multiple lines my code is not taking new line character
      No ratings available.
      Left on 11/9/2006 5:09:24 PM by Anonymous
      Comments: Thanks a lot, it is very nice an easy. Note: It did not work for me initially as I was using Sorting. I disabled Sorting and it worked fine. You may want to mention this in the article.
      Left on 9/11/2006 4:58:01 AM by Anonymous
      Comments: Thanx alot, it is very nice easy to understand
      Left on 8/22/2006 8:13:09 PM by Anonymous
      Comments: Thanks a bunch,it helped me to save lots of time
      Left on 8/10/2006 11:04:00 AM by Anonymous
      Comments: It worked for me. However I would like to know how to disable the open button.
      Left on 8/4/2006 7:56:43 AM by Anonymous
      Comments: this code is not comfortable for IE
      No ratings available.
      Left on 7/27/2006 6:35:26 AM by Anonymous
      Comments: You are a genious. Excellent work..Pooja
      Left on 7/14/2006 1:17:37 AM by Anonymous
      Comments: It works on the debug mode however when it is hosted, I can't seem to download the file using IE. Could you tell me why?
      Left on 7/6/2006 7:43:14 AM by Anonymous
      Comments: I have an error message when i click on the button:
      An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
      Left on 6/22/2006 2:09:10 PM by Anonymous
      Comments: its an excellent article, really very helpful
      Left on 5/31/2006 11:59:29 AM by Anonymous
      Comments: this article really helpful
      No ratings available.
      Left on 5/31/2006 2:38:49 AM by Anonymous
      Comments: good, But I use Spire.DataExport. http://www.e-iceblue.com.
      Left on 5/10/2006 5:45:10 AM by Anonymous
      Comments: Thank you!!
      No ratings available.
      Left on 4/26/2006 5:06:15 PM by Anonymous
      Comments: Yap, this is what we all need
      thanks
      Left on 4/20/2006 6:58:49 AM by Anonymous
      Comments: thankksss a lootsssss...gr8 work
      No ratings available.
      Left on 4/18/2006 7:13:32 AM by Anonymous
      Comments: Hi, This is what i am exactly looking for ....Thank you so much
      Left on 2/15/2006 4:08:38 AM by Anonymous
      Comments: Comments from the following blog: Office Software Tricks, located at: http://www.office-software-tricks.com/archives/18-In-just-one-Box.html
      No ratings available.
      Left on 9/13/2005 1:59:23 AM by Anonymous
      Comments: Perfectly Organized and simple explanation.
      Keep up the good job.
      No ratings available.
      Left on 9/12/2005 2:41:04 PM by Anonymous
      Comments: Can you please post more info on how to fix the formatting issue ? It is not working for me. Thanks
      Left on 9/6/2005 4:27:39 AM by Anonymous
      Comments: the format code sucks all's
      Left on 8/24/2005 10:48:23 AM by Anonymous
      Comments: When I added the code to export to excel it opens a blank excel sheet..???
      mikedandy@erie-thamespower.com
      Left on 8/18/2005 11:24:46 AM by Anonymous
      Comments: I am glad that you liked it. Please also visit www.gridviewguy.com for more of my articles.

      Thanks,
      No ratings available.
      Left on 8/18/2005 8:22:35 AM by Anonymous
      Comments: Great Code... Just Copy Pasted and it worked... Thanks a Lot!!!
      No ratings available.
      Left on 8/11/2005 6:33:22 PM by Anonymous
      Comments: Great Mnn!! Thanks to all the people like u.
      Left on 8/10/2005 10:50:56 AM by Anonymous
      Comments: Great article.  I took some of this code and was able to write an export to excel that has multiple worksheets in the workbook.  Thanks.
      Left on 8/2/2005 4:01:22 PM by Anonymous
      Comments: But can I pull data (text) from multiple text boxes in a word doc into an excel sheet?
      No ratings available.
      Left on 7/27/2005 3:34:24 PM by Anonymous
      Comments: This article is great!
      No ratings available.
      Left on 7/20/2005 12:18:32 PM by Anonymous
      Comments: It should work since I am also using Bound Columns.
      No ratings available.
      Left on 7/16/2005 5:01:48 AM by Anonymous
      Comments: Very good & simple.
      But... I tried using BoundColumn object for adding columns into DataGrid, and set AutoGenerateColumns to FALSE. It seems failed to export from DataGrid, any reason why?? Kas.
      Left on 6/28/2005 12:47:57 PM by Anonymous
      Comments: Thanks,
      :)
      AzamSharp
      No ratings available.
      Left on 6/28/2005 12:39:40 PM by Anonymous
      Comments: really helpful. Keep up the good work.
      No ratings available.
           
           

       

       

           
           

       


       


      Digg This
       


      DotNetNuke Platinum Benefactor

       


       


      Digg This
       


      DotNetNuke Platinum Benefactor

           
           

      Other family network sites: santry.com - katieandkarleigh.com

      Powered by 

       

           
      Copyright 20010 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970
      Privacy Statement | Terms Of Use