01
protected
void
btnExportToExcel_Click(
object
sender, EventArgs e)
02
{
03
if
(RadioButtonList1.SelectedIndex == 0)
04
{
05
GridView1.ShowHeader =
true
;
06
GridView1.GridLines = GridLines.Both;
07
GridView1.AllowPaging =
false
;
08
GridView1.DataBind();
09
}
10
else
11
{
12
GridView1.ShowHeader =
true
;
13
GridView1.GridLines = GridLines.Both;
14
GridView1.PagerSettings.Visible =
false
;
15
GridView1.DataBind();
16
}
17
18
ChangeControlsToValue(GridView1);
19
Response.ClearContent();
20
21
Response.AddHeader(
"content-disposition"
,
"attachment; filename=GridViewToExcel.xls"
);
22
23
Response.ContentType =
"application/excel"
;
24
25
StringWriter sWriter =
new
StringWriter();
26
27
HtmlTextWriter hTextWriter =
new
HtmlTextWriter(sWriter);
28
29
HtmlForm hForm =
new
HtmlForm();
30
31
GridView1.Parent.Controls.Add(hForm);
32
33
hForm.Attributes[
"runat"
] =
"server"
;
34
35
hForm.Controls.Add(GridView1);
36
37
hForm.RenderControl(hTextWriter);
38
39
Response.Write(sWriter.ToString());
40
41
Response.End();
42
}
43
44
private
void
ChangeControlsToValue(Control gridView)
45
{
46
Literal literal =
new
Literal();
47
48
for
(
int
i = 0; i < gridView.Controls.Count; i++)
49
{
50
if
(gridView.Controls[i].GetType() ==
typeof
(LinkButton))
51
{
52
53
literal.Text = (gridView.Controls[i]
as
LinkButton).Text;
54
gridView.Controls.Remove(gridView.Controls[i]);
55
gridView.Controls.AddAt(i,literal);
56
}
57
else
if
(gridView.Controls[i].GetType() ==
typeof
(DropDownList))
58
{
59
literal.Text = (gridView.Controls[i]
as
DropDownList).SelectedItem.Text;
60
61
gridView.Controls.Remove(gridView.Controls[i]);
62
63
gridView.Controls.AddAt(i,literal);
64
65
}
66
else
if
(gridView.Controls[i].GetType() ==
typeof
(CheckBox))
67
{
68
literal.Text = (gridView.Controls[i]
as
CheckBox).Checked ?
"True"
:
"False"
;
69
gridView.Controls.Remove(gridView.Controls[i]);
70
gridView.Controls.AddAt(i,literal);
71
}
72
if
(gridView.Controls[i].HasControls())
73
{
74
75
ChangeControlsToValue(gridView.Controls[i]);
76
77
}
78
79
}
80
81
}