5,696,576 members and growing! (19,006 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate

Exporting DataGrid to Excel, Word and Text Files

By azamsharp

How to export DataGrid to Excel, Word and Text files.
C#, VB, Windows, .NET, Visual Studio, ASP.NET, ADO.NET, WebForms, Dev

Posted: 21 Jul 2005
Updated: 21 Jul 2005
Views: 259,506
Bookmarked: 172 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
30 votes for this Article.
Popularity: 6.40 Rating: 4.33 out of 5
2 votes, 6.7%
1
1 vote, 3.3%
2
3 votes, 10.0%
3
4 votes, 13.3%
4
20 votes, 66.7%
5

Introduction

DataGrid is one of the most coolest controls in ASP.NET. One thing that all developers need is to put the DataGrid data into an Excel sheet. In this article I will show you how you can export your DataGrid data to an Excel file, a Word file and also a text file.

Exporting DataGrid to Excel

Exporting DataGrid to Excel might sound complex but it's 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 a DataGrid to an Excel file:

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

As you can see, exporting a DataGrid to an Excel file is pretty simple.

Exporting the DataGrid to a Word file

You can also export a DataGrid to a Word file. You might ask a question that why would anyone like to do that. If you have a Word document which needs a table, then you can simply export the table from the DataGrid to the Word document. The code is similar to the above with 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();

Exporting a DataGrid to a Text File

Sometimes you need to export a DataGrid to a Text file. In this case you need to iterate through the DataSet and concatenate the text to a string or more precisely a 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 iterate through the DataSet and append the rows into the StringBuilder object.

Format Issue when Exporting DataGrid to Excel

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

When you export a DataGrid to Excel it loses its format. This means that maybe your DataGrid has a string field which consisted of numbers, say '002345'. But when you export the grid and see it in an 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 AsString
Dim oStringWriter AsNew System.IO.StringWriter
Dim oHtmlTextWriter AsNew System.Web.UI.HtmlTextWriter(oStringWriter)
Dim objStreamWriter As StreamWriter
Dim strStyle AsString = "<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 about 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 AsString = "<style>.text { mso-number-format:\@; } </style>"
For intTemp AsInteger = 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 opening an Excel file and typing a 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 what style the column SSN uses. 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 a complete discussion on this issue, please visit this link.

I hope you liked the article, happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

azamsharp


I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.

HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.

ScreencastADay is a website committed to educate you everyday. The idea of the website is really simple. We believe that in order to be successful you need to learn something new everyday. ScreencastADay puts this thought into action by providing new screencast every day. This means you will get 7 screencasts a week and 365 screencasts a year unless of course it is a leap year in that case you get one more bonus screencast.

HighOnCoding.com www.HighOnCoding.com

ScreencastADay.com: www.ScreencastADay.com

RefactorCode: www.RefactorCode.com

GridViewGuy: GridViewGuy

My Blog:

Blog

Occupation: Web Developer
Location: United States United States

Other popular ASP.NET Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 95 (Total in Forum: 95) (Refresh)FirstPrevNext
GeneralProblem exporting datagrid to excelmemberAnu78718hrs 36mins ago 
GeneralExport to wordmemberMember 36797331:09 13 Nov '08  
GeneralExport table cell to Excel - Unicode characters are not being displayed correctlymemberMember 395040112:13 18 Sep '08  
GeneralResponse. XXXXXXXmemberAtis12:15 16 Sep '08  
GeneralGrid to Excel Export in ASP.Netmembersukanya_rathinam0:40 7 Aug '08  
GeneralExport multiple datagrids on single sheet side by sidememberilja g22:15 16 Jul '08  
GeneralServer cannot append header after HTTP headers have been sentmemberMember 226819421:49 16 Jun '08  
Generalwhat about numbers being stored as text?memberMember 392631211:27 16 May '08  
GeneralHow to Export all data from grid having custom pagingmembersameer_s19:49 16 Apr '08  
QuestionDatatable export problem..0's are getting ommitted at few places..memberprashobkumar0:28 8 Apr '08  
QuestionError in Export Excellmembersanjsy21:52 19 Mar '08  
AnswerRe: Error in Export Excell [modified]memberFrankie4u23:38 15 May '08  
QuestionHow to export gridveiw to excel with multiple sheetmemberShrikanth Saripella23:24 10 Mar '08  
AnswerRe: How to export gridveiw to excel with multiple sheetmemberBarbaMariolino0:50 4 Jun '08  
GeneralVisual Studio??memberdoxari17:04 20 Feb '08  
QuestionException in the code pls help memembervivekanandaraj3:38 19 Oct '07  
Generalhellomemberwild ron18:24 3 Sep '07  
GeneralRe: hellomemberazamsharp18:58 3 Sep '07  
Questionimport slides using ASP.netmembermyvi666923:28 8 Aug '07  
QuestionIf Grid is having Paging then Following Code gets errormemberRajesh Indalkar1:08 27 Jun '07  
GeneralExcel>SaveAs defaults to .html not .xlsmemberElizabeth Gee9:16 6 Jun '07  
QuestionIs it possible to close original window?memberMariaE5:24 25 May '07  
QuestionNew worksheet in excel filememberbonina_8:10 18 Apr '07