一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ASP.NET导出数据到Excel实现程序

时间:2013-07-23 编辑:简简单单 来源:一聚教程网

一、定义文档类型、字符编码

 代码如下 复制代码
   Response.Clear();
   Response.Buffer= true;
   Response.Charset="utf-8";  
   //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
   //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm  
   Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");  
//Response.ContentType指定文件类型 可以为application/ms-excel application/ms-word    application/ms-txt    application/ms-html 或其他浏览器可直接支持文档 
   Response.ContentType = "application/ms-excel";
   this.EnableViewState = false;  

 
二、定义一个输入流  

 代码如下 复制代码
   system.IO.StringWriter oStringWriter = new system.IO.StringWriter();
   system.Web.UI.HtmlTextWriter oHtmlTextWriter = new system.Web.UI.HtmlTextWriter(oStringWriter);

三、将目标数据绑定到输入流输出  

 代码如下 复制代码
   this.RenderControl(oHtmlTextWriter);
   //this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件  
   Response.Write(oStringWriter.ToString());
   Response.End();

四、 这时如果发生"只能在执行 Render() 的过程中调用 RegisterForEventValidation"的错误提示。

有两种方法可以解决:
 
1.修改web.config(不推荐)
2.直接在导出Execl的页面修改 


好了说了一大堆放了,下面我们来看利用.net的类型“GridView”的控件“ctl00_center_GridView1”必须放在具有 runat=server 的窗体标记内。 说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息:System.Web.HttpException: 类型“GridView”的控件“ctl00_center_GridView1”必须放在具有 runat=server 的窗体标记内。

这段错误描述是我在注释了这段程序是报的错,

 代码如下 复制代码

//publicoverridevoidVerifyRenderingInServerForm(Controlcontrol)
//{
//  //base.VerifyRenderingInServerForm(control);
//}

  虽然这个方法里的内容也被注释了,也就是说这是个空方法,但是如果没有个方法,程序就会报上面那个错误。最初见到这段错误说明是想到了以前做ajax程序时报的一个错误很是类似。同样是因为没有重写VerifyRenderingInServerForm方法所致。在此提醒使用的朋友注意,下面贴出导出到Excel的代码

 

 代码如下 复制代码
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.IO;
///
///ToExcleHelper的摘要说明
///

  publicclassExportHelper
  {
    publicstaticvoidExportToExcel(IListdataList,string[]fields,string[]headTexts,stringtitle)
    {
      GridViewgvw=newGridView();
      intColCount,i;
      //如果筛选的字段和对应的列头名称个数相对的情况下只导出指定的字段
      if(fields.Length!=0&&fields.Length==headTexts.Length)
      {
        ColCount=fields.Length;
        gvw.AutoGenerateColumns=false;
        for(i=0;i         {
          BoundFieldbf=newBoundField();
          bf.DataField=fields[i];
          bf.HeaderText=headTexts[i];
          gvw.Columns.Add(bf);
        }
      }
      else
      {
        gvw.AutoGenerateColumns=true;
      }
      SetStype(gvw);
      gvw.DataSource=dataList;
      gvw.DataBind();
      ExportToExcel(gvw,title);
    }
    ///
    ///导出数据到Excel
    ///

    ///IListData
    ///要导出的字段
    ///字段对应显示的名称
    publicstaticvoidExportToExcel(IListdataList,string[]fields,string[]headTexts)
    {
      ExportToExcel(dataList,fields,headTexts,string.Empty);
    }
    ///
    ///设置样式
    ///

    ///
    privatestaticvoidSetStype(GridViewgvw)
    {
      gvw.Font.Name="Verdana";
      gvw.BorderStyle=System.Web.UI.WebControls.BorderStyle.Solid;
      gvw.HeaderStyle.BackColor=System.Drawing.Color.LightCyan;
      gvw.HeaderStyle.ForeColor=System.Drawing.Color.Black;
      gvw.HeaderStyle.HorizontalAlign=System.Web.UI.WebControls.HorizontalAlign.Center;
      gvw.HeaderStyle.Wrap=false;
      gvw.HeaderStyle.Font.Bold=true;
      gvw.HeaderStyle.Font.Size=10;
      gvw.RowStyle.Font.Size=10;
    }
    ///
    ///导出GridView中的数据到Excel
    ///

    ///
    ///
    publicstaticvoidExportToExcel(GridViewgvw,stringtitle)
    {
      stringfileName;
      HttpContext.Current.Response.Buffer=true;
      HttpContext.Current.Response.ClearContent();
      HttpContext.Current.Response.ClearHeaders();
      fileName=string.Format("xhmd{0:yyMMddHHmm}.xls",DateTime.Now);
      HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+fileName);
      HttpContext.Current.Response.ContentType="application/vnd.ms-excel";
      StringWritertw=newSystem.IO.StringWriter();
      HtmlTextWriterhw=newSystem.Web.UI.HtmlTextWriter(tw);
      gvw.RenderControl(hw);
      if(!string.IsNullOrEmpty(title))
      {
        HttpContext.Current.Response.Write("
"+title+"
");
      }
      HttpContext.Current.Response.Write(tw.ToString());
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.Close();
      HttpContext.Current.Response.End();
      gvw.Dispose();
      tw.Dispose();
      hw.Dispose();
      gvw=null;
      tw=null;
      hw=null;
    }
    publicstaticvoidDataTable2Excel(System.Data.DataTabledtData)
    {
      System.Web.UI.WebControls.DataGriddgExport=null;
     //当前对话
      System.Web.HttpContextcurContext=System.Web.HttpContext.Current;
      //IO用于导出并返回excel文件
      System.IO.StringWriterstrWriter=null;
      System.Web.UI.HtmlTextWriterhtmlWriter=null;
      if(dtData!=null)
     {
        //设置编码和附件格式
       curContext.Response.ContentType="application/vnd.ms-excel";
       curContext.Response.ContentEncoding=System.Text.Encoding.UTF8;
       curContext.Response.Charset="";
        
        //导出excel文件
       strWriter=newSystem.IO.StringWriter();
       htmlWriter=newSystem.Web.UI.HtmlTextWriter(strWriter);
       //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
        dgExport=newSystem.Web.UI.WebControls.DataGrid();
        dgExport.DataSource=dtData.DefaultView;
        dgExport.AllowPaging=false;
        dgExport.DataBind();
        //返回客户端
        dgExport.RenderControl(htmlWriter);  
        curContext.Response.Write(strWriter.ToString());
        curContext.Response.End();
      }
    }
  }

总结,最后这个带了可以操作分页导出的,相对文章开始来说是复杂了许多哦。

热门栏目