.Net中導出數據到Excel(asp.net和winform程序中)
2024-07-10 12:46:31
供稿:網友
一、asp.net中導出Excel的方法:
在asp.net中導出Excel有兩種方法,一種是將導出的文件存放在服務器某個文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸出時,t分隔的數據,導出Excel時,等價于分列,n等價于換行。
1、將整個html全部輸出Excel
此法將html中所有的內容,如按鈕,表格,圖片等全部輸出到Excel中。
代碼如下:
Response.Clear();
Response.Buffer= true;
Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");
Response.ContentEncoding=System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
這里我們利用了ContentType屬性,它默認的屬性為text/html,這時將輸出為超文本,即我們常見的網頁格式到客戶端,如果改為ms-excel將將輸出excel格式,也就是說以電子表格的格式輸出到客戶端,這時瀏覽器將提示你下載保存。ContentType的屬性還包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我們也可以輸出(導出)圖片、word文檔等。下面的方法,也均用了這個屬性。
2、將DataGrid控件中的數據導出Excel
上述方法雖然實現了導出的功能,但同時把按鈕、分頁框等html中的所有輸出信息導了進去。而我們一般要導出的是數據,DataGrid控件上的數據。
代碼如下:
System.Web.UI.Control ctl=this.DataGrid1;
//DataGrid1是你在窗體中拖放的控件
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
如果你的DataGrid用了分頁,它導出的是當前頁的信息,也就是它導出的是DataGrid中顯示的信息。而不是你select語句的全部信息。
為方便使用,寫成方法如下:
代碼如下:
public void DGToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);