Click here to Skip to main content
11,429,777 members (71,466 online)
Click here to Skip to main content

Exporting DataGrid to Excel, Word and Text Files

, 21 Jul 2005
Rate this:
Please Sign up or sign in to vote.
How to export DataGrid to Excel, Word and Text files.

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

Share

About the Author

azamsharp
Web Developer
United States United States
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.

HighOnCoding.com www.HighOnCoding.com


My Blog:

Blog



Buy my iPhone app ABC Pop

Comments and Discussions

 
QuestionHow to export dataset to Excel with Multiple worksheet in ASP.Net Pin
Chad Sesbreno4-Jul-14 0:00
memberChad Sesbreno4-Jul-14 0:00 
GeneralMy vote of 5 Pin
gaga blues2-Nov-12 5:04
membergaga blues2-Nov-12 5:04 
QuestionError Glasses.Test.DataGridExport Pin
Member 87961717-Apr-12 16:29
memberMember 87961717-Apr-12 16:29 
QuestionFree library, to export from a DataSet into a real Excel 2007 .xlsx using OpenXML Pin
MikeGledhill1-Dec-11 2:38
memberMikeGledhill1-Dec-11 2:38 
AnswerRe: Free library, to export from a DataSet into a real Excel 2007 .xlsx using OpenXML Pin
Chris G.27-Mar-12 10:43
memberChris G.27-Mar-12 10:43 
QuestionLarge data import Pin
nikunjmochi16-Oct-11 23:16
membernikunjmochi16-Oct-11 23:16 
Questionexporting gridview along with some text at the top of the sheet Pin
jyoti mahalik10-Feb-11 21:33
memberjyoti mahalik10-Feb-11 21:33 
GeneralPC vs Mac Pin
Joe Sweeney28-Jul-10 12:06
memberJoe Sweeney28-Jul-10 12:06 
GeneralExporting Grid to Plain Text Pin
shyjup4-Jun-10 8:27
membershyjup4-Jun-10 8:27 
Generaldivision of cell in datagrid Pin
pujabhatia20109-Mar-10 3:17
memberpujabhatia20109-Mar-10 3:17 
QuestionDo you have a code for VB.NET that do the same thing? Pin
Nire Memu4-May-09 2:48
memberNire Memu4-May-09 2:48 
I need to export datagrid to excel using VB.NET. Please help me.
QuestionRe: Do you have a code for VB.NET that do the same thing? Pin
RavinderSingroha15-May-09 4:45
memberRavinderSingroha15-May-09 4:45 
AnswerRe: Do you have a code for VB.NET that do the same thing? Pin
CikaPero8-Sep-10 3:02
memberCikaPero8-Sep-10 3:02 
GeneralChange Format without Looping Pin
Member 260326726-Mar-09 21:31
memberMember 260326726-Mar-09 21:31 
GeneralRe: Change Format without Looping Pin
azamsharp27-Mar-09 5:43
memberazamsharp27-Mar-09 5:43 
GeneralRe: Change Format without Looping Pin
Member 438356512-May-09 11:46
memberMember 438356512-May-09 11:46 
GeneralHelp Pin
Saranya.Zy1-Mar-09 21:42
memberSaranya.Zy1-Mar-09 21:42 
Questionproblem in export datagrid to excel Pin
meg2220-Feb-09 0:28
membermeg2220-Feb-09 0:28 
GeneralHelp.... Pin
Chris O'N22-Jan-09 4:28
memberChris O'N22-Jan-09 4:28 
NewsNot the right way Pin
chandan10013-Dec-08 6:07
memberchandan10013-Dec-08 6:07 
GeneralRe: Not the right way Pin
azamsharp3-Dec-08 9:20
memberazamsharp3-Dec-08 9:20 
GeneralRe: Not the right way Pin
CikaPero15-Sep-10 23:25
memberCikaPero15-Sep-10 23:25 
GeneralProblem exporting datagrid to excel Pin
Anu7872-Dec-08 0:43
memberAnu7872-Dec-08 0:43 
GeneralThanks Pin
nellairahul26-Feb-09 18:40
membernellairahul26-Feb-09 18:40 
GeneralRe: Problem exporting datagrid to excel Pin
pramodsrujani26-Dec-09 2:21
memberpramodsrujani26-Dec-09 2:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150428.2 | Last Updated 21 Jul 2005
Article Copyright 2005 by azamsharp
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid