将GridView显示的内容导出为Excel

 

1.      在页面文件里有一个GridView,假定ID为GridView_CheckStat

2.      用户访问到GridView显示的内容之后点击一个导出按钮

3.      方法如下:

         引入:using System.IO;

    /// <summary>
    /// 导出为Excel
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    protected void Button_ExportExcel_Click(object sender, EventArgs e)
    {
        string style = @"<style> .text { mso-number-format:\@; } </script> ";
        Response.ClearContent();
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AddHeader("content-disposition", "attachment; filename=ExcelFile.xls");
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        //假定我们要导出的GridView的ID为GridView_CheckStat
        //导出前将GridView排序和分页都关闭
        GridView_CheckStat.AllowPaging = false;
        GridView_CheckStat.AllowSorting = false;
        //从页面取到查询条件
        string materialType = this.txtMaterialType.Text;
        string depotType = this.DropDownList_DepotType.SelectedValue;
        string depotId = this.DropDownList_Depot.SelectedValue;
        string goodsName = this.txtGoodsName.Text.Trim();
        //填充数据源
        GridView_CheckStat.DataSource = CheckStatBll.getCheckStatByCondition(materialType, depotId, depotType, goodsName);
        //绑定数据源
        GridView_CheckStat.DataBind();
        GridView_CheckStat.RenderControl(htw);
        //Style为导出Excel时的格式(有个五六种吧,去网上查一下)
        Response.Write(style);
        Response.Write(sw.ToString());
        Response.End();
        //导出前将GridView分页打开
        GridView_CheckStat.AllowPaging = true;
        GridView_CheckStat.AllowSorting = false;
        //重新绑定数据源
        GridView_CheckStat.DataBind();
    }

4.      导出Excel防止出错,重写一个方法

/// <summary>
/// 重写一下,导出为excel时不会报错
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{    }

5.      现在就可以让用户看到导出的Excel文件了。但是想要定义某一列显示的数据格式,如一列为money,一列为两位小数,或是一列为整数,一列为日期等,类似这些格式可以放在GridView的一个事件RowDataBound中来定义如下:

    /// <summary>
    /// GridView_CheckStat加入行变化样式
     /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    protected void GridView_CheckStat_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标在某一行上方时激发
            e.Row.Attributes.Add("onmouseover", "curColor=this.style.backgroundColor;this.style.backgroundColor='#DDCCAA'");
            //当鼠标从某一行上方移开时激发
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=curColor");
            //导出Excel时文本化
            //e.Row.Cells[1].Attributes.Add("class", "text"); 
            //这里的[0]代表第一列
            e.Row.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        }
    }

你可能感兴趣的:(String,object,Excel,Class,button)