首先要把GridView控件放到panel中
AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" OnRowDeleting="gridview1_RowDeleting"
OnRowEditing="gridview1_RowEditing" DataKeyNames="sno" OnDataBound="gridview1_DataBound"
Font-Size="14px">
DataNavigateUrlFormatString="StudentInfo.aspx?id={0}" />
再添加一個(gè)按鈕,,用于觸發(fā)導(dǎo)出事件:
以上為aspx頁(yè)面代碼,,后臺(tái)代碼則是:
protected void lbtnexcel_Click(object sender, EventArgs e)
{
gridview1.BottomPagerRow.Visible = false;//導(dǎo)出到Excel表后,,隱藏分頁(yè)部分
gridview1.Columns[9].Visible = false;//隱藏“編輯”列
gridview1.Columns[10].Visible = false;//隱藏“刪除”列
DateTime dt = DateTime.Now;//給導(dǎo)出后的Excel表命名,,結(jié)合表的用途以及系統(tǒng)時(shí)間來(lái)命名
string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
/*如導(dǎo)出的表中有某些列為編號(hào),、身份證號(hào)之類(lèi)的純數(shù)字字符串,,如不進(jìn)行處理,,則導(dǎo)出的數(shù)據(jù)會(huì)默認(rèn)為數(shù)字,,例如原字符串"0010"則會(huì)變?yōu)?B style="BACKGROUND-COLOR: #ff66ff; COLOR: black">數(shù)字10,,字符串"1245787888"則會(huì)變?yōu)榭茖W(xué)計(jì)數(shù)法1.236+E9,這樣便達(dá)不到我們想要的結(jié)果,,所以需要在導(dǎo)出前對(duì)相應(yīng)列添加格式化的數(shù)據(jù)類(lèi)型,,以下為格式化為字符串型*/
foreach (GridViewRow dg in this.gridview1.Rows)
{
dg.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
dg.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
dg.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
dg.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("學(xué)生表" + filename, System.Text.Encoding.UTF8) + ".xls");//導(dǎo)出文件命名
Response.ContentEncoding = System.Text.Encoding.UTF7;//如果設(shè)置為"GB2312"則中文字符可能會(huì)亂碼
Response.ContentType = "applicationshlnd.xls";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
Panel1.RenderControl(oHtmlTextWriter);//Add the Panel into the output Stream.
Response.Write(oStringWriter.ToString());//Output the stream.
Response.Flush();
Response.End();
}
//重載VerifyRenderingInServerForm方法,,否則運(yùn)行的時(shí)候會(huì)出現(xiàn)如下錯(cuò)誤提示:“類(lèi)型“GridView”的控件“GridView1”必須放在具有 runat=server 的窗體標(biāo)記內(nèi)”
public override void VerifyRenderingInServerForm(Control control)
{
//override VerifyRenderingInServerForm.
}