關于ASP.NET 將數據導出成Excel 的總結[上]
由于項目需要,必須實現將ASP.NET 中的網格數據或者數據集中的數據導出成Excel 文件。
在博客園里尋找了一陣子,發現幾篇不錯的文章:
A. 林子的“Excel讀寫管理類庫ExcelManager” 對Excel文件的讀寫不錯
ExcelManager -- 基于.Net的Excel讀寫管理類庫(一)
ExcelManager--基于.Net的Excel讀寫管理類庫(二)
B. henry的基于EXCEL 的WEB 報表輸出組件 也不錯,
只是IE的安全設置不允許運行未標記為安全的activeX控件,需要更改IE的安全設置。
C. 如果只是將頁面“網格控件”當前頁所顯示的數據導出成Excel 文件,那GridView 導出Excel 研究 非常不錯了。
全文如下:
=========================================================================================
Introduction:
將GridView中的數據導出為Excel是web應用中的常見功能。在不同的應用場景下有不同的導出技術。在本文中我將介紹一些導出的技術,希望對您有所幫助
GridView Export the Excel (Basic Code):
首先看一個基礎的應用。創建一個表格,見截圖
然后將數據庫中的數據綁定到GridView中的數據,代碼如下:
|
private void BindData() { SqlConnection myConnection = new SqlConnection("Server=localhost;Database=School;Trusted_Connection=true"); SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Users", myConnection); DataSet ds = new DataSet(); ad.Fill(ds); gvUsers.DataSource = ds; gvUsers.DataBind(); } |
現在,GridView中已經綁定了數據,接下來的任務就是導出到Excel。下面是button事件中的代碼
|
Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvUsers.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); |
并且還需要override一下VerifyRenderingInServerForm方法(這一點非常重要,否則在點擊按鈕后會報錯,譯者注),代碼如下:
|
public override void VerifyRenderingInServerForm(Control control) { } |
點擊導出按鈕后會彈出對話框,詢問您打開或保存。選擇打開文件,導出到Excel的結果如下圖:
Exporting GridView to Excel With Style:
您是否注意到了以上代碼存在一些的問題?是的,ID列開頭的0都被截去了。如果你的ID是000345,導出后就編程了345。這個問題可以通過把css添加到輸出流中來解決。為了使ID列正確顯示,您需要將其儲存為文本格式。Excel中的文本格式表示為"mso-number-format:"\@"。
|
protected void Btn_ExportClick(object sender, EventArgs e) { string style = @"<style> .text { } </script> "; Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvUsers.RenderControl(htw); // Style is added dynamically Response.Write(style); Response.Write(sw.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } |
在上面的代碼中,我通過”style”變量來控制GridView列的樣式。并通過Respnose.Write方法將其添加到輸出流中。最后把樣式添加到ID列。這一步需要在RowDataBound事件中完成
|
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[1].Attributes.Add("class", "text"); } } |
修改的結果如下:
Exporting GridView With LinkButtons and Paging:
如果要導出的GridView中包含LinkButton或者分頁(出現分頁碼時,譯者注) 則將出現錯誤:
通過修改頁文件可以修正這個問題:EnableEventValidation = "false".
|
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> |
看一下導出的文件
在導出的文件中可以看見linkbutton和dropdownlist控件,雖然dropdownlist控件顯示的數據的確是用戶所選的項,但怎么看也不像是一個導出文件(我倒是覺的挺cool的:)譯者注),現在應如何移除dropdownlist并顯示選擇的文字呢?
我寫了一個DisableControls函數,用使循環的方法將linkbutton和dropdownlist替換成literal控件
|
private void DisableControls(Control gv) { LinkButton lb = new LinkButton(); Literal l = new Literal(); string name = String.Empty; for (int i = 0; i < gv.Controls.Count; i++) { if (gv.Controls[i].GetType() == typeof(LinkButton)) { l.Text = (gv.Controls[i] as LinkButton).Text; gv.Controls.Remove(gv.Controls[i]); gv.Controls.AddAt(i, l); } else if (gv.Controls[i].GetType() == typeof(DropDownList)) { l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text; gv.Controls.Remove(gv.Controls[i]); gv.Controls.AddAt(i, l); }
if (gv.Controls[i].HasControls()) { DisableControls(gv.Controls[i]); } } } |
方法非常簡單,只需將linkbuton和dropdownlist替換成literal控件,并將選擇項賦值給literal控件的文本屬性。該方法需要在導出前調用
|
protected void Btn_ExportExcelPaging(object sender, EventArgs e) { DisableControls(gvUsers); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvUsers.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } |
現在的Excel中就只剩下選中文本了
代碼下載:GridViewExportToExcelAllYouNeed.zip
| 作者: XuGang 網名:鋼鋼 |
| 出處: http://xugang.cnblogs.com |
| 聲明: 本文版權歸作者和博客園共有。轉載時必須保留此段聲明,且在文章頁面明顯位置給出原文連接地址! |
浙公網安備 33010602011771號