ASP.NET導出數據到Excel的實現方法
2024-07-10 12:45:05
供稿:網友
網上好些代碼的原理大致與此類似,同樣都存在一個問題,就是:
類型“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>