C# gridview分頁導出excel

本文介绍了一种使用ASP.NET中的GridView控件将数据导出到Excel的方法。通过禁用分页并设置正确的字符集及文件头信息,可以确保数据正确地导出,并解决了在Excel 2007中可能出现的乱码问题。

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

  #region 导出Excel方法  
        //导出到Excel按钮   
        protected void btnExport_Click(object sender, EventArgs e)
        {
            Export("application/ms-excel", "字段数据.xls");
            
        } 

 
   private void Export(string FileType, string FileName)  
   {  
      //清楚分页   
       gridView.AllowPaging = false;
       BindData();  
       
       Response.Clear();  
        Response.Buffer = true;  
       //设定输出的字符集   
        Response.Charset = "GB2312";  
      //解决导出到Excel2007乱码问题   
       Response.Write("<meta http-equiv=Content-Type content=text/html;charset=GB2312>");  
 
        //假定导出的文件名为盘点结果表.xls   
        Response.AppendHeader("Content-Disposition", "attachment;filename=" +  
                             HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());  
       //解决导出到Excel2007乱码问题   
       Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");  

        //设置导出文件的格式   
      Response.ContentType = FileType;  
       //关闭ViewState   
     this.EnableViewState = false;
     System.IO.StringWriter stringWriter = new System.IO.StringWriter();  
      HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
      gridView.RenderControl(textWriter);  
      //把HTML写回浏览器   
       Response.Write(stringWriter.ToString());  
       Response.Flush();  
      Response.End();
      gridView.AllowPaging = true;//恢复分页   
       //为GridView重新绑定数据源   
      BindData();  
      
    }  
 
    //如果没有下面方法会报错,类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内(导出Excel或Word用)   
   public override void VerifyRenderingInServerForm(Control control)  
    {

    }
  #endregion

 

转载于:https://www.cnblogs.com/xw2cc1314/p/3282924.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值