此外做了个导出Excel的功能,主要代码如下:
1
private void DumpExcel(GridView gv, string FileName)
2
{//带格式导出
3
string style = @"<style> .text { mso-number-format:\@; } </script>";
4
Response.ClearContent();
5
Response.Charset = "GB2312";
6
Response.ContentEncoding = System.Text.Encoding.UTF8;
7
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
8
Response.ContentType = "application/excel";
9
StringWriter sw = new StringWriter();
10
HtmlTextWriter htw = new HtmlTextWriter(sw);
11
gv.RenderControl(htw);
12
// Style is added dynamically
13
Response.Write(style);
14
Response.Write(sw.ToString());
15
Response.End();
16
}
17
public override void VerifyRenderingInServerForm(Control control)
18
{
19
}
20
上面的行17的重载函数是必须的,否则会报“GridView要在有run=server的From体内”的错。
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

此外,变量style的作用是控制GridView列的样式,避免发生excel表中字符前导0被当成数字给截掉这样的问题, 通过Response.Write方法将其添加到输出流中。最后把样式添加到ID列。这一步需要在RowDataBound事件中完成:
1
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
2
{
3
if (e.Row.RowType == DataControlRowType.DataRow)
4
{
5
e.Row.Cells[1].Attributes.Add("class", "text");
6
}
7
}

2

3

4

5

6

7
