遗失的星空

导航

【Wonder原创】GridView导出Excel格式控制一

一、前台页面:

 

代码
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo._Default" %>
2
3  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5  <html xmlns="http://www.w3.org/1999/xhtml" >
6  <head runat="server">
7 <title></title>
8 </head>
9 <body>
10 <form id="form1" runat="server">
11 <div>
12 <asp:GridView ID="gvUsers" runat="server" onrowdatabound="gvUsers_RowDataBound">
13 </asp:GridView>
14 <br />
15 <asp:Button ID="btnExport" runat="server" onclick="btnExport_Click" Text="导出" />
16 </div>
17 </form>
18 </body>
19 </html>

 

二、后台代码:

 

 

后台代码
public void BindData()
{
DataTable dt
= new DataTable();
dt.Columns.Add(
"WorkID", typeof(string));
dt.Columns.Add(
"EName", typeof(string));

DataRow dr
= dt.NewRow();
dr[
0] = "0706097";
dr[
1] = "Wonder Wang";

dt.Rows.Add(dr);

gvUsers.DataSource
= dt;
gvUsers.DataBind();
}

protected void btnExport_Click(object sender, EventArgs e)
{
string style = @"<style> .text { mso-number-format:\@; } </script> ";

Response.ClearContent();
Response.AddHeader(
"content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType
= "application/excel";
StringWriter sw
= new StringWriter();
HtmlTextWriter htw
= new HtmlTextWriter(sw);

gvUsers.AllowPaging
= false;
BindData();

gvUsers.RenderControl(htw);

// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[
0].Attributes.Add("class", "text");
}
}

 

 

 

 

 

posted on 2010-07-26 14:55  遗失的星空  阅读(411)  评论(0编辑  收藏  举报