Dict.CN 在线词典, 英语学习, 在线翻译 ------------- MyGitee 朱秋贵内科诊所 My腾云code

gridview 导出Excel

 protected void btnImportData_Click(object sender, EventArgs e)
    {
        BTN_Query_Click(sender, e);
        BindStoreUserListImport(ViewState["sWhere"].ToString());
        setHiddenFiled(GridView1, false);
        setFiledFormat(GridView1);
        Export("application/ms-excel", "我需要的数据.xls");
        setHiddenFiled(GridView1, true);
    }

    private void Export(string FileType, string FileName)
    {
        Response.Clear();
        Response.Buffer = true;

        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        this.GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
        this.BindStoreUserList(Convert.ToInt32(ViewState["PageNo"]), ViewState["sWhere"].ToString());
    }

   

 

  //要导出的数据

    protected void BindStoreUserListImport(string swhere)
    {
        int index=0;
        DataSet ds = new DataSet();

        string strSQL = "select * from   table1 where " + swhere + " order by  SignDate desc";

        string strCount = "select count(Id) as total from table1 where " + swhere + "";
        SqlDataReader sdr = help.ExecuteReader(strSQL);
        object countObj = help.GetSingle(strCount);
        if (countObj != null)
        {
            index = Convert.ToInt32(countObj);
        }
        GridView1.DataSource = sdr;

        GridView1.DataBind();

    

        this.WebPager1.RecordCount = index; //分页控件
        this.WebPager1.PageSize = 20;
        this.WebPager1.CurrentPageIndex = 1;

    }

 

    必要的方法 不然会出错

    public override void VerifyRenderingInServerForm(Control control)
    {

    }

    隐藏不需要导出的字段
    protected  void setHiddenFiled(GridView gv,bool flag)
    {
        if (gv.Rows.Count > 0)
        {
            int cellLength = gv.Rows[0].Cells.Count;
            for (var i = 0; i < gv.Rows.Count; i++)
            {
                gv.Rows[i].Cells[cellLength - 2].Visible = flag;
            }
            gv.HeaderRow.Cells[cellLength - 2].Visible = flag;
        }

    }

 

 

 

    导出 格式化身份证号码或银行卡号
    protected void setFiledFormat(GridView gv)
    {
        for (int i =0; i <gv.Rows.Count; i++)
        {
            gv.Rows[i].Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            gv.Rows[i].Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        }
    }
posted @ 2009-10-23 14:39  cn2024  阅读(166)  评论(0编辑  收藏  举报