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:
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:
Ouput sample:
Don't forget to override the VerifyRenderingInServerForm method. For exporting each page must have override this method:
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:
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:
Output sample:
Export to Word:To export GridView data to ms-word just modify your button click event by the following code sample:
Export to Text:To export GridView data to a text file just modify your button click event by the following code sample:
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.
Output sample:
List of some useful mso-number-format:
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();
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();
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();
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();
{
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();
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();
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();
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:
Format | Description |
mso-number-format:"0" | NO Decimals |
mso-number-format:"0\.000" | 3 Decimals |
mso-number-format:"\#\,\#\#0\.000 | Comma 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
Post a Comment