GridView導出Excel

1.aspx頁面需要添加:EnableEventValidation="false"

實例:<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false"  CodeFile="DefCheckDate.aspx.cs"
    Inherits="WebAdmin_CustomRegister_ShortOverFlow_DefCheckDate" %>

2.後台代碼(實例):

public void btn_ExcelClick(object sender, EventArgs e)
    {
        if (Gdv_Sof.Rows.Count <= 0)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript'>alert('沒有數據!')</script>");
            return;
        }
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=CheckDate.xls");
        Response.ContentType="application/excel";
        Response.Charset = "Big5";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("Big5");
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        Gdv_Sof.Columns[0].Visible = false;
        Gdv_Sof.Columns[1].Visible = false;
        Gdv_Sof.HeaderRow.Controls.Clear();
         Gdv_Sof.AllowPaging = false;
        Gdv_Sof.AllowSorting = false;
        BindGridView();
        Gdv_Sof.RenderControl(htw);
        Response.Write(sw);
        Response.End();
        Gdv_Sof.AllowPaging = true;
        Gdv_Sof.AllowSorting = true;
        BindGridView();
     
 
    }

//此方法一定要有VerifyRenderingInServerForm
    public override void VerifyRenderingInServerForm(Control control)
    {
     }

3.導出的數據格式設置:例如頁面為005,可是導出卻為5,就需要添加以下樣式vnd.ms-excel.numberFormat:@");

實例:

protected void Gdv_Sof_RowDateBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberFormat:@");
            e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberFormat:@");
        }
    
    }

上一篇:Selenium图片上传


下一篇:中文分词算法之最大正向匹配算法(Python版)