Asp.net Gridview导出Excel

时间:2024-04-25 20:37:57

前台页面放一个GridView什么的就不说了,要注意的是在

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="ReferPriceIndex.aspx.cs" EnableEventValidation="false"
Inherits="ZTE.Fol.Fund.UI.Web.InsideTrade.ReferPrice.ReferPriceIndex" %>

标签里面加EnableEventValidation属性

同时后台加上

        /// <summary>
/// 内容摘要:重写空的VerifyRenderingInServerForm方法,避免在导出Excel文件的时候出现
/// “……必须放在具有 runat=server 的窗体标记内”的异常
/// 另外说明:
/// 在asp.net2.0中,控件的校验严格了,
/// RenderControl代码只有走正常流程在render方法中它自己调用才能成功,
/// 在自己写的事件方法中调用就会出现这个错误。
/// </summary>
/// <param name="control">提交控件</param>
public override void VerifyRenderingInServerForm(Control control)
{
}// end VerifyRenderingInServerForm

这两个地方都加上,可以防止导出excel的时候导出整个页面

BeadRollListExportExcel.aspx 页面就是导出的页面了,页面代码:
 <asp:GridView ID="GridView1" BorderColor="Black" runat="server" AutoGenerateColumns="False"
Font-Size="12px" Width="530px" AllowSorting="True"
OnRowCreated="GridView1_RowCreated">
<Columns>
<asp:TemplateField HeaderText="序号" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<%#(((GridViewRow)Container).DataItemIndex + 1) %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PrimarySchoolName" HeaderText="学校" />
<asp:BoundField DataField="TypeName" HeaderText="类别" />
<asp:BoundField DataField="Name" HeaderText="姓名" />
<asp:BoundField DataField="SexCode" HeaderText="性别" />
<asp:BoundField DataField="" HeaderText="备注" />
</Columns>
<HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" />
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>

后台代码:

    protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetList();
Export("application/ms-excel", string.Format("{0}****.xls", DateTime.Now.ToString("yyyy-MM-dd")));
}
} public void GetList()
{
string studentType = Request.QueryString["studentType"].ToString();
string schoolCode = Request.QueryString["schoolCode"].ToString();
string district = Request.QueryString["district"].ToString();
string strWhere = " 1=1";
if (!string.IsNullOrEmpty(studentType))
{
strWhere += " and TypeCode='" + studentType + "'";
}
if (!string.IsNullOrEmpty(district))
{
strWhere += " and DistrictCode='" + district + "'";
}
if (!string.IsNullOrEmpty(schoolCode))
{
strWhere += " and PrimarySchoolCode ='" + schoolCode + "'";
}
DataTable dt = new BLL.ObjMethod().GetList("View_ExportExcelStudent", strWhere); GridView1.DataSource = dt;
GridView1.DataBind();
} /// <summary>
/// 定义导出Excel的函数
/// </summary>
/// <param name="FileType"></param>
/// <param name="FileName"></param>
private void Export(string FileType, string FileName)
{
for (int i = ; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].Cells[].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlDecode(FileName, Encoding.UTF8).ToString());//HttpUtility.UrlDecode输出中文文件名称
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
/// <summary>
/// 此方法必重写,否则会出错
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{
} protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
//列头前面在加一行
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow rowHeader = new GridViewRow(, , DataControlRowType.Header, DataControlRowState.Normal);//表头行
TableHeaderCell cell = new TableHeaderCell();
cell.Text = "*****";
cell.ColumnSpan = ;
rowHeader.Cells.Add(cell);
((GridView)sender).Controls[].Controls.AddAt(, rowHeader);
}
}