Click here to Skip to main content
16,013,489 members
Articles / Web Development / ASP.NET
Article

Exporting DataGrid to Excel, Word and Text Files

Rate me:
Please Sign up or sign in to vote.
4.63/5 (41 votes)
21 Jul 20053 min read 834.2K   11.9K   256   125
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.

C#
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.

C#
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:

C#
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:

VB
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.

VB
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


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
GeneralFormattingof Excel File Pin
shoaib_aleem31-May-06 2:56
shoaib_aleem31-May-06 2:56 
GeneralExport to a predefine path Pin
Pepsi330ml29-May-06 19:04
Pepsi330ml29-May-06 19:04 
GeneralRe: Export to a predefine path Pin
lauralucas11-Jul-06 9:53
lauralucas11-Jul-06 9:53 
QuestionError:Server cannot append header after HTTP headers have been sent. Pin
Gavish George29-May-06 5:36
Gavish George29-May-06 5:36 
GeneralGood Job Pin
niuniu23_198210-May-06 21:29
niuniu23_198210-May-06 21:29 
GeneralMicrosoft.Office.Interop.Excel Pin
prof_martin14-Mar-06 15:13
prof_martin14-Mar-06 15:13 
GeneralExport to new window Pin
Pradeep K V14-Feb-06 23:16
Pradeep K V14-Feb-06 23:16 
QuestionError exporting to Excel Pin
IWantToDownload12-Feb-06 17:16
IWantToDownload12-Feb-06 17:16 
Exception Details: System.Web.HttpException: Control 'dgrdProjects_ctl02_ctl00' of type 'DataGridLinkButton' must be placed inside a form tag with runat=server.



I read one of the previous posts, but couldn't get this to work properly. I did convert your code to VB:

Sub ExportToExcel(s As Object, e As EventArgs)
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.xls"

Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As New HtmlTextWriter(stringWrite)

dgrdProjects.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.End()

End Sub

Any ideas on how to help?


Thanks in advance...

--------------------------------------------------------------------
Error Message in full:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Control 'dgrdProjects_ctl02_ctl00' of type 'DataGridLinkButton' must be placed inside a form tag with runat=server.
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.Web.HttpException: Control 'dgrdProjects_ctl02_ctl00' of type 'DataGridLinkButton' must be placed inside a form tag with runat=server.

Source Error:


Line 242: Dim htmlWrite As New HtmlTextWriter(stringWrite)
Line 243:
Line 244: dgrdProjects.RenderControl(htmlWrite)
Line 245: Response.Write(stringWrite.ToString())
Line 246: Response.End()


Source File: c:\inetpub\wwwroot\RobertASPNET\BBNCOP\MainView.aspx Line: 244

Stack Trace:


[HttpException (0x80004005): Control 'dgrdProjects_ctl02_ctl00' of type 'DataGridLinkButton' must be placed inside a form tag with runat=server.]
System.Web.UI.Page.VerifyRenderingInServerForm(Control control) +1997535
System.Web.UI.WebControls.LinkButton.AddAttributesToRender(HtmlTextWriter writer) +37
System.Web.UI.WebControls.WebControl.RenderBeginTag(HtmlTextWriter writer) +17
System.Web.UI.WebControls.DataGridLinkButton.Render(HtmlTextWriter writer) +24
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +130
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +24
System.Web.UI.WebControls.TableCell.RenderContents(HtmlTextWriter writer) +97
System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +29
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +130
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +24
System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +7
System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +29
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
System.Web.UI.WebControls.Table.RenderContents(HtmlTextWriter writer) +605
System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +29
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +130
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +24
System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +7
System.Web.UI.WebControls.BaseDataList.Render(HtmlTextWriter writer) +27
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
ASP.robertaspnet_bbncop_mainview_aspx.ExportToExcel(Object s, EventArgs e) in c:\inetpub\wwwroot\RobertASPNET\BBNCOP\MainView.aspx:244
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102


------------------------------------------------


Robert
GeneralWork With VS 2005 Pin
mtone23-Jan-06 6:47
mtone23-Jan-06 6:47 
GeneralRe: Work With VS 2005 Pin
azamsharp23-Jan-06 8:33
azamsharp23-Jan-06 8:33 
GeneralRe: Work With VS 2005 Pin
mtone23-Jan-06 12:24
mtone23-Jan-06 12:24 
GeneralRe: Work With VS 2005 Pin
filimon30-Jan-06 10:10
filimon30-Jan-06 10:10 
GeneralRe: Work With VS 2005 Pin
Lalit N Dubey11-Mar-06 0:03
Lalit N Dubey11-Mar-06 0:03 
GeneralRe: Work With VS 2005 Pin
azamsharp23-Nov-06 5:52
azamsharp23-Nov-06 5:52 
GeneralExport in new pages Pin
Mussi20-Dec-05 2:42
Mussi20-Dec-05 2:42 
QuestionProblem with Excel Export in Win XP Pro Pin
virsum1-Dec-05 4:20
virsum1-Dec-05 4:20 
GeneralRe: Problem with Excel Export in Win XP Pro Pin
virsum1-Dec-05 6:08
virsum1-Dec-05 6:08 
GeneralRe: Problem with Excel Export in Win XP Pro Pin
azamsharp1-Dec-05 15:09
azamsharp1-Dec-05 15:09 
GeneralRe: Problem with Excel Export in Win XP Pro Pin
khoadd24-Jul-06 15:56
khoadd24-Jul-06 15:56 
GeneralRe: Problem with Excel Export in Win XP Pro Pin
AndresY20-May-08 13:29
AndresY20-May-08 13:29 
Generalexporting to word Pin
Member 21892969-Oct-05 14:58
Member 21892969-Oct-05 14:58 
GeneralRe: exporting to word Pin
azamsharp9-Oct-05 16:24
azamsharp9-Oct-05 16:24 
GeneralRe: exporting to word Pin
Member 21892969-Oct-05 17:20
Member 21892969-Oct-05 17:20 
Generalother way (XLS) Pin
Jan Gex27-Sep-05 1:43
Jan Gex27-Sep-05 1:43 
GeneralRe: other way (XLS) Pin
fuhaizah13-Jul-06 18:31
fuhaizah13-Jul-06 18:31 

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

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