Datagrid export to excel, text file and word file
By AzamSharp
Views: 16341

 Introduction:

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 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 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 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 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 !

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Formatting Excel Output
Name: Karen Grube
Date: 2/10/2007 7:12:26 PM
Comment:
Hi!

I was wondering if you could please revise the source code sample to include an example of how to use the style code from Juss. I can't figure out where to place that code in relation to the code used to the gridiew export to Excel.

Thanks!
Karen Grube
Subject: Export to Excel
Name: Charles Evans
Date: 3/29/2007 9:27:28 AM
Comment:
My Datagrid displays rows in different colors due to the value in a column field. How can export the rows to Excel, with the colors they have in the Datagrid?
Subject: Namespaces
Name: JimScalia
Date: 4/12/2007 10:46:35 AM
Comment:
I get the c# error StringWriter cannot be found. Am I missing a namespace?

Thanks,

Jim Scalia
scalia@home.win.net
Subject: RE: Namespaces
Name: AzamSharp
Date: 4/12/2007 12:59:41 PM
Comment:
Hi,

You need to add System.IO. Something like this:

using System.IO;
Subject: save to text
Name: dabros
Date: 8/2/2007 4:24:19 AM
Comment:
System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

what for?

there is no connection between streams and response object!
Subject: Error when creating report in word
Name: Manish
Date: 8/22/2007 3:25:41 AM
Comment:
Hi,


We have encounter a problem while we
use your code.
The error is as follows
"Gridview must be placed in form tag
with runat = server"
Such kind of error is generated tell me
how can i solve this problem.
please reply quick and
(2) where we put this code in which event in asp.net(C#).
Subject: how to export data from gridview to excel,word where gridview provide features of paging and sorting
Name: manish
Date: 8/23/2007 3:46:42 AM
Comment:
hi,

I use above code(it work in simple gridview). But it doesn't work in gridview with features of paging and sorting. I use template fields, boundfields, and itemtemplate with hyperlink facility, so how i can now export my gridview data to word, excel and text file.

Reply me quickly, pls pls
Subject: RE: Exporting Datagrid with Sorting And Paging
Name: AzamSharp
Date: 8/25/2007 8:58:51 PM
Comment:
Hi Manish,

For paging you can turn it off right before you are trying to export the Datagrid. You can also refer to the following article in which I replace all the LinkButtons to the Literal control right before the export takes place.

http://thedotnetguy.com/ArticleDetails.aspx?articleID=197
Subject: Problem in above code
Name: KEVALSING RAJPUT
Date: 10/1/2007 10:42:57 PM
Comment:
hi,
your code helped me a lot.
but it has some problem.
code works fine when we click on export button once.
but when we click on it next time new browser instance opens but the contents of previous instance are gone.

can u explain why?
Subject: Error on rendering the gridView
Name: Siva S
Date: 10/30/2007 12:24:10 AM
Comment:
Hi,

I used the code for Exporting the data to excel.
but Getting the below error when i Rendering the gridview.

Control 'GridVwResults' of type 'GridView' must be placed inside a form tag with runat=server.

Please help me in solving this problem.
Subject: msnavigation tag wrecks havoc on export to excel
Name: CodePosta
Date: 11/7/2007 10:47:27 AM
Comment:
One issue I've recently discovered is that excel and / or word will skip rows of data and even mix up column values of any of the exported data contains the FrontPage Markup tag Don't ask me why I'm sure its a Microsoft thing... just thought I'd share and help some of you that may read this why exporting is wonky sometimes...

--Posta
Subject: Error
Name: JD
Date: 11/14/2007 9:59:38 PM
Comment:
I can't seem to figure out this error:

Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Subject: Cannot get Word working
Name: Greenie
Date: 11/16/2007 10:19:13 AM
Comment:
I am also having this error: "type 'GridView' must be placed inside a form tag with runat=server."

It only occurs when exporting to Word. Excel is working wonderfully. Please let me know how to fix this!!!


Subject: RE: Cannot get word working!
Name: AzamSharp
Date: 11/19/2007 7:14:07 AM
Comment:
Hi Greenie, That is strange! Try putting enableEventValidation = false for the page directive.
Subject: used exportToexcel code and faced problem
Name: Dhananjay
Date: 11/30/2007 12:54:25 AM
Comment:
hi all
i have used the code given for exportToexcel ( i;e; from gridview to excel) but i faced problem.
my problem is i am able to get the data but problem is there are some controls placed on the page like label,textbox and buttons, i don't want these controls appeared in excel file, but all the controls which on my web page they are coming into excel file too.how can i solve the problem.please let me know
Thanks in advancve
Dhananjay
Subject: Exporting Datagrid to Excel
Name: Imran
Date: 11/30/2007 9:05:22 PM
Comment:
Hi,
My code-behind is VB,how can export the rows in excel,how to use the code in my code behind?
Subject: Formatting Excel cell
Name: Surjit
Date: 12/11/2007 10:55:24 PM
Comment:
Hi,

this is really a helpful post.
My Problem was that if phone numberr column is not having any spaces in the number and it exceeds the cell width, then that number was shown in form of chineese charactes.
After implementing format for that column, problem was solved.

thanks a lot
Surjit
Subject: Problem exporting when the grid is added in a web part
Name: Nilotpal
Date: 2/5/2008 10:40:43 PM
Comment:
I have added a grid and a export button in a web part. The web part is added in a sharepoint page. When I try to export for the first time it works fine and then its not working. It seems to me that the page is not posted back for the second time. Any help will be appreciated.
Subject: TEXT file
Name: Isiaka Wasiu
Date: 3/31/2008 3:35:52 AM
Comment:
Pls, I need assistance, I used VB to write script that generate a text file, using Notepad ++ you find that that all column align but when you open the file with frontpage using html format. html tab. some of the column especial with a non static length colud not align even though they are still in the right colun in their row.
Can some one help me out



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008