五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > 將GridView中的數(shù)據(jù)導(dǎo)出到EXCEL

將GridView中的數(shù)據(jù)導(dǎo)出到EXCEL

文章來(lái)源:365jz.com     點(diǎn)擊數(shù):269    更新時(shí)間:2011-05-07 21:01   參與評(píng)論
  在后臺(tái)進(jìn)行數(shù)據(jù)查詢操作時(shí),我們可能會(huì)使用GridView控件進(jìn)行數(shù)據(jù)展示,有時(shí)需要將GridView控件中顯示的數(shù)據(jù)導(dǎo)出到EXCEL文件中,通過(guò)調(diào)用GridView控件的RenderContol方法將數(shù)據(jù)導(dǎo)出到字符流中進(jìn)行輸出。
  首先為GridView控件設(shè)置數(shù)據(jù)源,并進(jìn)行綁定操作,然后在導(dǎo)出按鈕添加如下點(diǎn)擊事件代碼。
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AppendHeader(
"Content-Disposition", "attachment;filename=FileName.xls");
//設(shè)置輸出流為簡(jiǎn)體中文
Response.Charset = "GB2312";
Response.ContentEncoding
= System.Text.Encoding.GetEncoding("GB2312");
//設(shè)置輸出文件類型為excel文件。
Response.ContentType = "application/ms-excel";
StringWriter sw
= new StringWriter();
HtmlTextWriter htw
= new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
  現(xiàn)在點(diǎn)擊導(dǎo)出按鈕頁(yè)面會(huì)報(bào)錯(cuò)誤,“類型“GridView”的控件“GridView1”必須放在具有 runat=server 的窗體標(biāo)記內(nèi)”。 這個(gè)需要在頁(yè)面中添加對(duì)VerifyRenderingInServerForm方法的重寫,就可以成功導(dǎo)出數(shù)據(jù)了。
public override void VerifyRenderingInServerForm(Control control)
{
}
  當(dāng)我們導(dǎo)出的數(shù)據(jù)為數(shù)字時(shí),比如編號(hào)或者身份證號(hào)碼,發(fā)現(xiàn)導(dǎo)出的數(shù)據(jù)中,編號(hào)前面的0沒(méi)了,身份證號(hào)碼變成了科學(xué)計(jì)數(shù)法。這個(gè)可以在GridView的RowDataBound事件處理函數(shù)中為導(dǎo)出的數(shù)字列添加一個(gè)樣式就可以了。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//第二列為身份證號(hào)碼
e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
}
}
  當(dāng)GridView存在分頁(yè)時(shí),這時(shí)候?qū)С鰯?shù)據(jù)的時(shí)候頁(yè)面也會(huì)報(bào)錯(cuò),“只能在執(zhí)行 Render() 的過(guò)程中調(diào)用 RegisterForEventValidation;” 。這個(gè)需要在<%@ Page   %>中設(shè)置EnableEventValidation="false"就可以了。
 

如對(duì)本文有疑問(wèn),請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答!! 點(diǎn)擊進(jìn)入論壇

發(fā)表評(píng)論 (269人查看,0條評(píng)論)
請(qǐng)自覺(jué)遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
昵稱:
最新評(píng)論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學(xué)習(xí)

業(yè)務(wù)咨詢

· 技術(shù)支持
· 服務(wù)時(shí)間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號(hào)