ASP.NET利用存储过程调用及下载类实现导出电子表格功能

这段代码展示了在ASP.NET中如何实现从GridView控件导出数据到Excel文件的过程。当用户点击按钮时,程序首先根据用户选择筛选数据,然后执行SQL查询获取库存信息,最后将数据绑定到GridView并使用自定义方法`DGToExcel`生成Excel文件供用户下载。这个方法清空了响应缓冲区,设置Content-Disposition和Content-Type头,以确保文件能正确下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    protected void btn_export_Click(object sender, EventArgs e)
    {
        int i_whlist = chk_whlist.SelectedIndex;
        string s_whlist = "";
        string _ws = "";
        if (i_whlist >= 0)
        {
            foreach (ListItem li in chk_whlist.Items)
            {
                s_whlist += li.Selected ? li.Value + "," : "";
            }
            _ws = s_whlist.Substring(0, s_whlist.Length - 1);
        }
        
        string _txtkey = txt_key.Text.ToString() == "" ? "" : txt_key.Text.ToString();
        string str_sql = "P_GET_IMSTOCKICInventory " + "'" + _ws + "'" + "," + "'" + _txtkey + "'";

        string _wh = chk_whlist.SelectedValue;
        string _dt=_wh+"-"+DateTime.Now.ToOADate().ToString();
        MydB rb = new MydB();
        DataTable dt = new DataTable();
        dt = rb.ExecuteQueryERP(str_sql);
        this.gv_export.DataSourceID = null;
        this.gv_export.DataSource = dt;
        this.gv_export.DataBind();
        mysubmenu.DGToExcel(this.gv_export, _dt);
        this.gv_export.Visible = false;
    }

    public override void VerifyRenderingInServerForm(Control control)
    {

    }//以上程序段必须添加否则会报错!

//以下是表格下载类

        //excel表格下载
        public void DGToExcel(System.Web.UI.Control ctl,string filename)
        {
           
            string _filename = filename.ToString();
            string ny = DateTime.Now.Date.ToString("yyyyMMdd");
            HttpContext.Current.Response.Clear();//清除缓冲区流中的所有的内容输出
            HttpContext.Current.Response.Buffer = true;//获取一个值,该值指示是否缓冲输出,并在完成处理整个响应之后将其发送

            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + _filename + ny + ".xls");
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            ctl.Page.EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            ctl.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();

        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值