本文執行個體講述了asp.net實現Gradview綁定資料庫資料並匯出Excel的方法。分享給大家供大家參考,具體如下:
protected void showData_Click(object sender, EventArgs e){ SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=test;User ID=sa;password=sa"); SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM booklist", myConnection); DataSet ds = new DataSet(); ad.Fill(ds); this.gvShowData.DataSource = ds; this.gvShowData.DataBind();}//匯出Excel表protected void btnExportToExcel_Click(object sender, EventArgs e){ Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.AddHeader("Content-Type", "application/vnd.ms-excel"); Response.AddHeader("Content-Disposition", "myexcelfile.xls"); //以此編碼模式匯出才不會出現亂碼 StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvShowData.RenderControl(htw); Response.Write(sw.ToString()); Response.End();}//一定要寫,否則出錯!!public override void VerifyRenderingInServerForm(Control control){}
希望本文所述對大家asp.net程式設計有所協助。