码迷,mamicode.com
首页 > 其他好文 > 详细

GridView導出Excel

时间:2015-11-11 13:08:58      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

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:@");
        }
    
    }

GridView導出Excel

标签:

原文地址:http://www.cnblogs.com/AnnyGird-LiMing/p/4955608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!