C#導出數據到Excel或者Word中的代碼片段
private void Page_Load(object sender, System.EventArgs e) { SqlConnection con=new SqlConnection("server=.;database=pubs;uid=sa;pwd=;"); con.Open(); SqlDataAdapter sda=new SqlDataAdapter(); sda.SelectCommand=new SqlCommand("select * from txtInsert",con); DataSet ds=new DataSet(); sda.Fill(ds,"emp"); this.DgSource.DataSource=ds.Tables["emp"]; this.DgSource.DataBind(); con.Close(); }public void DataGridToExcel(DataGrid grdTemp,DataSet dsTemp) { grdTemp.AllowPaging=false; //設置不能分頁
grdTemp.DataSource=dsTemp; //重新綁定數據源 grdTemp.DataBind(); //常規導出方法 System.IO.StringWriter SW = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter HTW=new System.Web.UI.HtmlTextWriter(SW); grdTemp.RenderControl(HTW); //Page為要導出的對象,當前是Page,如果是DataGrid,DataList等都可以 Response.Buffer=true; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/vnd.ms-excel"; //Response.ContentType是輸出流的 HTTP MIME 類型 //Response.ContentType --- word文件 //application/vnd.ms-excel --- excel文件 // Response.Charset="utf-8"; Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8"); Response.AddHeader("Content-Disposition", "attachment;filename=aaa.xls"); //attachment --- 作為附件下載 //inline --- 在線打開 //filename如過是中文,則可以用HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) //進行進行編碼,以解決文件名亂碼的問題 Response.Write(SW.ToString()); Response.Flush(); Response.Close(); }
private void Button1_Click(object sender, System.EventArgs e) { SqlConnection con=new SqlConnection("server=.;database=pubs;uid=sa;pwd=;"); con.Open(); SqlDataAdapter sda=new SqlDataAdapter(); sda.SelectCommand=new SqlCommand("select * from txtInsert",con);
DataSet ds=new DataSet(); sda.Fill(ds,"emp"); this.DgSource.DataSource=ds.Tables["emp"];
this.DataGridToExcel(this.DgSource,ds); con.Close(); }</pre>
本文由用戶 wen5 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!