Skip to main content

GridView Export data to Excel,Word, & Text file

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 & replaceforeach (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

Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality. I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons. Customers and Orders Table of Northwind Database are used to populate nested GridViews. Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview. Place another grid in last templateField column. Markup of page after adding both templatefields will like as shown below. HTML SOURCE 1: < asp:GridView ID ="gvMaster" runat ="server" 2: AllowPaging ="True" 3: AutoGenerateColumns ="False" 4: DataKeyNames ="CustomerID" 5: DataSour

Add Edit Update Records in GridView using Modal Popup in ASP.Net

Add Edit Update Records in GridView using Modal Popup in ASP.Net In this article, I’ll explain how to Add and Edit records in ASP.Net GridView control using ASP.Net AJAX Control Toolkit Modal Popup Extender. Database For this tutorial, I am using Microsoft’s NorthWind database. You can download it using the following link. Download Northwind Database Connection string Below is the connection string to connect to the database. < connectionStrings >     < add name = " conString "      connectionString = " Data Source=.\SQLExpress;database=Northwind;     Integrated Security=true " /> </ connectionStrings >   HTML Markup Below is the HTML Markup of the page. Below you will notice that I have placed a Script Manager and an ASP.Net Update Panel on the page. Inside the Update Panel I have placed an ASP.Net GridView Control along with a Modal Popup Extender that will be used to Add or Edit the records in the GridView