Tuesday, March 10, 2009

Export GridView data to Excel,Word, & Text file




Please visit my new Web Site WWW.Codedisplay.com



Exporting GridView data to Excel,Word, & Text file is a very common task which is performed in most of the asp.net web applications to meet the customized reporting purposes. There are various techniques of exporting the GridView to excel and it highly depends on the application scenario. I will show you that how you can export your GridView data to Excel file, Word file and also Text file. When exporting keep the format of data is a very frequent requirement and also user might want to set different format which i will discuss in the later section of this post. So lets start with direct export to excel. Atfirst we need to create a table in sql server database. Table looks like:










Now we need to add a page. Add a GridView, Button in our page to export data. Now page design is completed. So now we need to bind data to the GridView first. Write the below code under Page_Load event to read data from sql server table:

SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;");
SqlDataAdapter Sqlad = new SqlDataAdapter("SELECT * FROM tblSupplier", myConnection);
DataSet dsSupplier = new DataSet();
Sqlad.Fill(dsSupplier);
gvEdit.DataSource = dsSupplier;
gvEdit.DataBind();


Now run the page hope you will see the below image keep in mind that we don't implement export functionality yet:



OK now the display part of this example is completed. Now try to export data in different file types.

Export to Excel:
To do that write the below code under export button click event:

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType =
"application/vnd.xls";
System.IO.
StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.
HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();


Ouput sample:


Don't forget to override the VerifyRenderingInServerForm method. For exporting each page must have override this method:

public override void VerifyRenderingInServerForm(Control control) { }



Export to Excel when GridView has paging:
Its a little bit tricky to export data when GridView has Paging functionality. Just set the AllowPaging property to False beforeexporting data. Now export button click event code like:

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.AllowPaging = false;
DataTable dtSupplier = (DataTable)ViewState["dtSupplier"];
gvEdit.DataSource = dtSupplier;
gvEdit.DataBind();
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();



Export to Excel when GridView contains control:
Replace corresponding GridView cells by controls value. Let you have a supplier list & you wantto display each supplier location as well as you want a facility that when user open thelist then user can see the regions other suppliers in a popup. To do that you have to add a link button in your GridView so that user can click on the link to view the other suppliers. Alsoyou have to export region value to Excel file. So how you can handle. Answer is replace the cell valueby link text just before exporting. Code sample:

//Read each GridView Row Data by itearation & replace
foreach (GridViewRow oItem in gvEdit.Rows)
{
LinkButton lnk=((LinkButton)oItem.FindControl("lnk"));
oItem.Cells[4].Text=lnk.Text;
lnk.Visible = false;
// Remove other controls like radio,dropdown or html controls also in the above way
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();


Output sample:


Export to Word:
To export GridView data to ms-word just modify your button click event by the following code sample:

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.doc");
Response.ContentType = "application/vnd.word";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();



Export to Text:
To export GridView data to a text file just modify your button click event by the following code sample:

//Always use StringBuilder for string operations it will enhance the performence
System.Text.StringBuilder str = new System.Text.StringBuilder();
foreach (GridViewRow oItem in gvEdit.Rows)
{
for (int j = 0; j <= oItem.Cells.Count- 1; j++)
str.Append(oItem.Cells[j].Text+" ");
str.Append("\r\n");
}
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=SupplierList.txt");
Response.ContentType = "application/vnd.text";
Response.Write(str.ToString());
Response.End();



Export to Excel with proper fomatting:
Hope from above example now one can easily export data from GridView. But an important concern is to setthe formatting to the target file. In this reagard mso-number-format ease our life. Lets we need todisplay date & time in the GridView but we wants short date format when exporting. To do the one can use mso-number-format in the following way. Modify your export button click event by the following code segment.

string datestyle = @"<style>.date { mso-number-format:'Short Date'; }</style>";
foreach(GridViewRow oItem in gvEdit.Rows)
oItem.Cells[4].Attributes.Add("class","date");
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
Response.Write(datestyle);
gvEdit.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();



Output sample:



List of some useful mso-number-format:
FormatDescription
mso-number-format:"0"NO Decimals
mso-number-format:"0\.000"3 Decimals
mso-number-format:"\#\,\#\#0\.000Comma with 3 dec
mso-number-format:"mm\/dd\/yy"Date7
mso-number-format:"mmmm\ d\,\ yyyy"Date9
mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM"Date -Time AMPM
mso-number-format:"Short Date"04/07/2008
mso-number-format:"Medium Date"04-Jun-08
mso-number-format:"d\-mmm\-yyyy"04-Jun-2008
mso-number-format:"Short Time"4:49
mso-number-format:"Medium Time"4:49 am
mso-number-format:"Long Time"4:49:13:00
mso-number-format:"Percent"Percent with two dec.
mso-number-format:"0%"Percent with no dec.
mso-number-format:"0\.E+00"Scientific Notation
mso-number-format:"\@"Text
mso-number-format:"\#\ ???/???"Fractions up to 3 digits
mso-number-format:"\0022£\0022\#\,\#\#0\.00"£10.52
mso-number-format:"0\.0000";font-weight:700;4 dec.+multiple format

Note:
If you do not find your required format from above list then try creating a spreadsheet with a single cell entry according to your required format. Then from file menu select the 'Save as Web Page' option to create a html file. Read & examine the code for this and findout the mso-number-format from the style declarations.
***Click for more details on GridView Column Formatting in my another article

8 comments:

Anonymous said...

hello,
I am trying your your code and get the following error

The name 'gvEdit' does not exist in the current context

thanks in advanced

Saion Roy said...

Hi,
At first sorry for my late response. I was very busy last week.

OK my guess is either you copied html code from another page or try to reference the gridview which is in a template column.

If you copied html code from another page then detach the page, close editor , Open editor again & rebind the page. Hope the page reference as weel as GridView reference will be updated.

If you use GridView in a template column then use findcontrol method to identify the grid first.

Anonymous said...

Hey...
Your codes were really usefull for bigginers. As i m bigginer, it helped me a lot........


Thanx Brightly Calister

Anonymous said...

i tried ur code but promt error "Invalid Object Name Sheet1$"

swapna said...

How to make header visible in each page exported in word?

Saion Roy said...

Good question Swapna. Basically using this code its not possible. You have to use framework 3.5 or upper. Lot of MS document related methods defined in new frameworks with appropriate documentation which is absent in 2.0. So study that since i didn't study yet.

Anonymous said...

M getting the blank text file....

Anonymous said...

It works well enough to get going. Now, if you have an idea how to export into a word document or pdf, it will be great!

for tpinting out the header row just add the following code:

Dim str As New System.Text.StringBuilder()
For i As Integer = 0 To GridView1.HeaderRow.Cells.Count - 1
str.Append(GridView1.HeaderRow.Cells(i).Text + ", ")
Next
str.Append(vbCr & vbLf)

Here is the complete procedure:
Public Sub exportInCSV()
Dim str As New System.Text.StringBuilder()
For i As Integer = 0 To GridView1.HeaderRow.Cells.Count - 1
str.Append(GridView1.HeaderRow.Cells(i).Text + ", ")
'str.Append(vbCr & vbLf)
Next
str.Append(vbCr & vbLf)
For Each oItem As GridViewRow In GridView1.Rows
For j As Integer = 0 To oItem.Cells.Count - 1
If oItem.Cells(j).Text.Contains("=") Then
Continue For
End If
str.Append(oItem.Cells(j).Text + ", ")
Next
str.Append(vbCr & vbLf)
Next
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.txt")
Response.ContentType = "application/vnd.text"
Response.Write(str.ToString())
Response.[End]()
End Sub

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash