本文是通过查看http://www.cnblogs.com/stswordman/archive/2006/08/24/485641.html的例子的修改,具体步骤看上面的链接就可以了
1
//绑定数据的部分
2
private void ExcelGridView()
3
{
4
Order order = new Order();//函数类
5
6
grdFOrderSearch.DataSource = order.QueryConsignList_FW();//查询函数
7
8
grdFOrderSearch.DataBind();
9
}
10
//在导出Excel中,移除GridView中用到控件,只以数据的形式导出
11
private void DisableControls(Control gv)
12
{
13
LinkButton lb = new LinkButton();
14
Literal l = new Literal();
15
string name = String.Empty;
16
17
for (int i = 0; i < gv.Controls.Count; i++)
18
{
19
if (gv.Controls[i].GetType() == typeof(LinkButton))
20
{
21
l.Text = (gv.Controls[i] as LinkButton).Text;
22
gv.Controls.Remove(gv.Controls[i]);
23
gv.Controls.AddAt(i, l);
24
}
25
else if (gv.Controls[i].GetType() == typeof(VesselLinkButton) //其中VesselLinkButton为自定义控件
26
{
27
l.Text = (gv.Controls[i] as VesselLinkButton).Text;
28
gv.Controls.Remove(gv.Controls[i]);
29
gv.Controls.AddAt(i, l);
30
}
31
else if (gv.Controls[i].GetType() == typeof(HyperLink))
32
{
33
l.Text = (gv.Controls[i] as HyperLink).Text;
34
gv.Controls.Remove(gv.Controls[i]);
35
gv.Controls.AddAt(i, l);
36
}
37
if (gv.Controls[i].HasControls())
38
{
39
DisableControls(gv.Controls[i]);
40
}
41
42
}
43
44
}
45
46
//此句不可少
47
public override void VerifyRenderingInServerForm(Control control)
48
{ }
49
50
protected void grdFOrderSearch_RowDataBound(object sender, GridViewRowEventArgs e)
51
{
52
if (e.Row.RowType == DataControlRowType.DataRow)
53
{
54
//正确显示以零开头的数据项
55
e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
56
e.Row.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
57
}
58
}
59
60
//导出到Excel,如有分页可以导出全部数据
61
protected void btnExcel_Click(object sender, EventArgs e)
62
{
63
64
Response.ClearContent();
65
66
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
67
68
Response.ContentType = "application/excel";
69
70
StringWriter sw = new StringWriter();
71
72
HtmlTextWriter htw = new HtmlTextWriter(sw);
73
74
grdFOrderSearch.AllowPaging = false;
75
76
ExcelGridView();
77
78
DisableControls(grdFOrderSearch);
79
80
grdFOrderSearch.RenderControl(htw);
81
82
Response.Write(sw.ToString());
83
84
Response.End();
85
86
grdFOrderSearch.AllowPaging = true;
87
88
ExcelGridView();
89
90
}
91
如果有出现乱码的情况就加上这一句
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;