Home » ASP.NET » How to implement CSS style to GridView Export to Excel in ASP.NET ?

How to implement CSS style to GridView Export to Excel in ASP.NET ?

Abstract:
Exporting GridView to Excel is a very common task which is performed in most of the web applications. There are various techniques of exporting the GridView to excel and it highly depends on the application scenario. In this article I will demonstrate some techniques that you will find useful.


Introduction:

Exporting GridView to Excel is a very common task which is performed in most of the web applications. There are various techniques of exporting the GridView to excel and it highly depends on the application scenario. In this article I will demonstrate some techniques that you will find useful.

GridView Export the Excel (Basic Code): 

Let’s start with the basic export scenario. First, we need to populate the GridView with some data. I have created a custom table which has number of fields. You can check out the screen shot below.


Now, the next task is to populate the GridView with the data from the database. Check out the following code which uses the DataSet to populate the GridView. 

01 private void BindData()
02  

 

03 {
04  

 

05 SqlConnection myConnection = new SqlConnection(“Server=localhost;Database=School;Trusted_Connection=true”);
06  

 

07 SqlDataAdapter ad = new SqlDataAdapter(“SELECT * FROM Users”, myConnection);
08  

 

09 DataSet ds = new DataSet();
10  

 

11 ad.Fill(ds);
12  

 

13 gvUsers.DataSource = ds;
14  

 

15 gvUsers.DataBind();
16  

 

17 }

 


So, now the GridView is populated with the data. The next task is to export the GridView to excel. You can use the following code for the button click event.

01 Response.ClearContent();
02  

 

03 Response.AddHeader(“content-disposition”, “attachment; filename=MyExcelFile.xls”);
04  

 

05 Response.ContentType = “application/excel”;
06  

 

07 StringWriter sw = new StringWriter();
08  

 

09 HtmlTextWriter htw = new HtmlTextWriter(sw);
10  

 

11 gvUsers.RenderControl(htw);
12  

 

13 Response.Write(sw.ToString());
14  

 

15 Response.End();

 

You will also need to override the VerifyRenderingInServerForm method. Take a look at the code below:

 

1 public override void VerifyRenderingInServerForm(Control control)
2  

 

3 {
4  

 

5 }

 

When you click the Export to Excel (Default) button a dialog box will popup which will allow you to open or save the exported file. Select open the file and you will see the exported data in the excel spreadsheet. Take a look at the screen shot below which shows the exported GridView in excel spreadsheet.


Exporting GridView to Excel With Style:

Did you see the problem in the above exportation code? Yes, the leading zero’s were truncated. It means that if your ID was 000345 it will show up as 345. You can fix this problem by adding a CSS script to the output stream. In order for the ID column to appear correctly you need to store it as text. The text format in excel is represented by “mso-number-format:”@“. Once, you know the format you can append the style in the output stream. Check out the code below.

01 protected void Btn_ExportClick(object sender, EventArgs e)
02  

 

03 {
04  

 

05 string style = @”<style> .text { mso-number-format:@; } </style> “;
06  

 

07 Response.ClearContent();
08  

 

09 Response.AddHeader(“content-disposition”, “attachment; filename=MyExcelFile.xls”);
10  

 

11 Response.ContentType = “application/excel”;
12  

 

13 StringWriter sw = new StringWriter();
14  

 

15 HtmlTextWriter htw = new HtmlTextWriter(sw);
16  

 

17 gvUsers.RenderControl(htw);
18  

 

19 // Style is added dynamically
20  

 

21 Response.Write(style);
22  

 

23 Response.Write(sw.ToString());
24  

 

25 Response.End();
26  

 

27 }

 

As, you can see in the above code that I have used the string variable “style” to hold the style of the GridView column. And I used the Response.Write method to write the style to the output stream. The last thing that you need to do is to add the style to the ID column. This can be done in the RowDataBound event of the GridView control.

01 protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
02  

 

03 {
04  

 

05 if (e.Row.RowType == DataControlRowType.DataRow)
06  

 

07 {
08  

 

09 e.Row.Cells[1].Attributes.Add(“class”, “text”);
10  

 

11 }
12  

 

13 }

 

Now, when you export the GridView to excel your exported file will look something like this.


Finding Style for the Column

You can easily find the correct style for your GridView column by opening the exported excel file. Now, click on the column header and select “Format Cells”. This will present you with several options to format the cells. Select text from the list and save the file as .htm (webpage) file. Now, open the webpage in your browser and view the source. In the style section you will find different styles for the table cell (td element). Now, locate the ID column by doing a search on the source of the webpage. You will find a line like this:

1 <td class=xl27 width=35 style=’border-left:none;width:26pt’>ID</td></font></font></p><p><font face=”Verdana” size=”2″><font face=”Verdana” size=”2″>


As, you can see that the above table cell uses the class x127. Now, go to the styles section and find the x127. 

1 .xl27
2     {mso-style-parent:style0;

 

3     font-weight:700;
4     mso-number-format:”@”;

 

5     text-align:center;
6     vertical-align:middle;

 

7     border:.5pt solid black;
8     white-space:normal;}</font></font></p><p><font face=”Verdana” size=”2″><font face=”Verdana” size=”2″>


When you look up the .x127 you will find the format of the cell defined as mso-number-format:”@”;.  

Exporting GridView With LinkButtons and Paging: 

When you try to export the GridView which contains LinkButtons and Paging enabled then you might see the following error.


You can easily handle this error by going to the page source and turning the EnableEventValidation = “false”.

1 <%@ Page Language=”C#” EnableEventValidation=”false” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

 

But let’s take a look at the exported file.


As, you can see that the LinkButtons and DropDownLists are also exported with the GridView control. Although the DropDownList does display the correct user selections but it does not look good in the exported file. So, let’s see how we can remove the DropDownList and only display the selected text.

I have created a simple DisableControls method which iterates through the GridView control and replace all LinkButtons and DropDownLists with the Literal control.

01 private void DisableControls(Control gv)
02  

 

03 {
04  

 

05 LinkButton lb = new LinkButton();
06  

 

07 Literal l = new Literal();
08  

 

09 string name = String.Empty;
10  

 

11 for (int i = 0; i < gv.Controls.Count; i++)
12  

 

13 {
14  

 

15 if (gv.Controls[i].GetType() == typeof(LinkButton))
16  

 

17 {
18  

 

19 l.Text = (gv.Controls[i] as LinkButton).Text;
20  

 

21 gv.Controls.Remove(gv.Controls[i]);
22  

 

23 gv.Controls.AddAt(i, l);
24  

 

25 }
26  

 

27 else if (gv.Controls[i].GetType() == typeof(DropDownList))
28  

 

29 {
30  

 

31 l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
32  

 

33 gv.Controls.Remove(gv.Controls[i]);
34  

 

35 gv.Controls.AddAt(i, l);
36  

 

37 }
38  

 

39   
40  

 

41 if (gv.Controls[i].HasControls())
42  

 

43 {
44  

 

45 DisableControls(gv.Controls[i]);
46  

 

47 }
48  

 

49 }
50  

 

51 }

 

The idea is very simple just replace all the LinkButton and DropDownList controls with a Literal control and assign their selection to the Literal control Text property. You need to call this function before the exportation takes place.

01 protected void Btn_ExportExcelPaging(object sender, EventArgs e)
02  

 

03 {
04  

 

05 DisableControls(gvUsers);
06  

 

07 Response.ClearContent();
08  

 

09 Response.AddHeader(“content-disposition”, “attachment; filename=MyExcelFile.xls”);
10  

 

11 Response.ContentType = “application/excel”;
12  

 

13 StringWriter sw = new StringWriter();
14  

 

15 HtmlTextWriter htw = new HtmlTextWriter(sw);
16  

 

17 gvUsers.RenderControl(htw);
18  

 

19 Response.Write(sw.ToString());
20  

 

21 Response.End();
22  

 

23 }

 

Now, when you export the GridView you will only see the selected text. Check out the screen shot below which shows the effect.


Conclusion:

In this article you learned different ways to export the GridView to excel. I have attached the complete source code to download. I hope you liked this article, happy coding!



Leave a Reply

Your email address will not be published. Required fields are marked *

www.000webhost.com