ASP.NET匯出資料到Excel的實現方法_實用技巧

來源:互聯網
上載者:User
網上好些代碼的原理大致與此類似,同樣都存在一個問題,就是:
  類型“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;
///<summary>
///ToExcleHelper的摘要說明
///</summary>
  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<ColCount;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);
    }
    ///<summary>
    ///匯出資料到Excel
    ///</summary>
    ///<paramname="DataList">IListData</param>
    ///<paramname="Fields">要匯出的欄位</param>
    ///<paramname="HeadName">欄位對應顯示的名稱</param>
    publicstaticvoidExportToExcel(IListdataList,string[]fields,string[]headTexts)
    {
      ExportToExcel(dataList,fields,headTexts,string.Empty);
    }
    ///<summary>
    ///設定樣式
    ///</summary>
    ///<paramname="gvw"></param>
    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;
    }
    ///<summary>
    ///匯出GridView中的資料到Excel
    ///</summary>
    ///<paramname="gvw"></param>
    ///<paramname="DataList"></param>
    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("<b><center><fontsize=3face=Verdanacolor=#0000FF>"+title+"</font></center></b>");
      }
      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();
      }
    }
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.