前台頁面:
<
%@ page
language
="c#"
autoeventwireup
="true"
codefile
="exportdemo.aspx.cs"
inherits
="exportdemo" %
>
<
!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" ""
>
<
html
xmlns
="">
<
head
runat
="server"
>
<
title
>gridview匯出到excel或word檔案——周公的部落格:
title
>
head
>
<
body
>
<
form
id="form1"
runat
="server"
>
<
div>
<
asp:gridview
id="**personlist"
runat
="server"
autogeneratecolumns
="false"
>
<
columns
>
<
asp:boundfield
datafield
="id"
headertext
="編號"
/>
<
asp:boundfield
datafield
="name"
headertext
="姓名"
/>
<
asp:templatefield
headertext
="性別"
>
<
itemtemplate
>
<
%#eval("***").tostring()=
="true"?"男":"女" %
>
itemtemplate
>
asp:templatefield
>
<
asp:boundfield
datafield
="age"
headertext
="年齡"
/>
<
asp:templatefield
headertext
="婚否"
>
<
itemtemplate
>
<
%# boolean.parse(eval("married").tostring())==true?"是":"否" %
>
itemtemplate
>
asp:templatefield
>
columns
>
asp:gridview
>
<
asp:button
id="btntoexcel"
runat
="server"
onclick
="btntoexcel_click"
text
="匯出到excel"
/>
<
asp:button
id="btntoword"
runat
="server"
onclick
="btntoword_click"
text
="匯出到word"
/>
div>
form
>
body
>
html
>
後台**:
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
///
/// 程式說明:這是乙個gridview匯出成excel或者word檔案的例項。為了演示,我採用了自動生成datatable,然後繫結。
/// 同時為了初學者檢視**方便,關鍵處我都做了注釋。
/// 對程式說明,在asp.net 1.1中由於對控制項呈現不是很嚴格,所以無需override void verifyrenderinginserverform(control control)這個方法
/// 但在asp.net2.0中,控制項的校驗嚴格了,rendercontrol**只有走正常流程在render方法中它自己呼叫才能成功,
/// 在你自己寫的事件方法中呼叫就會出現這個錯誤。這個錯誤資訊有點誤導,你明明寫在伺服器控制項form內,它照樣會這樣提醒你,
/// 實際上是asp.net2.0設定了內部變數控制rendercontrol不允許在render方法之外被輕易呼叫。如果不override verifyrenderinginserverform
/// 就會報錯。我們override void verifyrenderinginserverform(control control)這個方法,裡面不寫任何**即可
/// 日期:2008-5-16
/// **:/zhoufoxcn
///
public partial
class exportdemo : system.web.ui.page
} void bindgridview() void bindgridview()
//手動生成datatable
datatable createdatatable() datatable createdatatable()
else
data.rows.add(datarow);
} return data;
} //override掉這個方法
override void verifyrenderinginserverform() override void verifyrenderinginserverform(control control)
void btntoexcel_click() void btntoexcel_click(object sender, eventargs e)
//匯出成word檔案
void btntoword_click() void btntoword_click(object sender, eventargs e)
}執行效果:
把Gridview中的資料匯出到Excel的通用類
把gridview中的資料匯出到excel 使用方式 1.如果是使用了updatepanel或在母版頁中使用了updatepanel,則在後台 的load裡面加上 scriptmanager.registerpostbackcontrol 匯出控制項按鈕 名稱即可 或 scriptmanager m...
帶母版頁的GRIDVIEW匯出到EXCEL方法
stringwriter sw new stringwriter htmltextwriter htw new htmltextwriter sw gridview1.rendercontrol htw response.write sw.tostring response.end gridview...
從 DataGridView 匯出到 Excel
public sub exporttoexcel byval datagridview1 as datagridview if datagridview1.rows.count 1 then for i 0 to datagridview1.columncount 1 生成excel中列頭名稱 my...