將 ASP .NET WebForm 的 DataGrid 中的資料 匯出至 Microsoft Excel
本文將逐步帶領您產生 ASP.NET WebForm 上的 DataGrid Web 伺服器控制項,然後將 DataGrid 內容匯出至 Microsoft Excel。
技術
本文將說明兩種匯出 DataGrid 資料的技術:
- 使用 Excel MIME 類型 (或內容類型)
您可以使用伺服器端的程式碼將 DataGrid 連結至資料,然後在用戶端電腦的 Excel 中開啟資料。如果要執行這項操作,請將 ContentType 設為 application/vnd.ms-excel 。用戶端收到新資料流後,資料會顯示在 Excel 中,如同在 Web 瀏覽器新網頁中開啟內容。
- 使用 Excel 自動化
您可以使用用戶端的程式碼,從 DataGrid 擷取成 HTML,然後「自動執行 Excel」以新的活頁簿顯示 HTML。「Excel 自動化」永遠會在 Excel 應用程式視窗的瀏覽器外側,顯示資料。「自動化」的一項優點是如果您想在匯出資料後修改活頁簿,可以由程式來控制 Excel。不過,由於 Excel 的指令碼是標示為不安全的,因此用戶端必須在 Web 瀏覽器上套用允許「自動化」的安全性設定。
逐步說明
- 啟動 Visual Studio .NET。在 [檔案] 功能表中,指向 [新增] ,再按一下 [專案] 。
- 按一下 [專案類型] 窗格中的 [Visual Basic 專案] 。按一下 [範本] 下的 [ASP.NET Web 應用程式] 。將應用程式命名為 ExcelExport ,然後按一下 [確定] 。
「設計」檢視中會出現 WebForm1。 3. 在「方案總管」的 [WebForm1.aspx] 上按右滑鼠鍵,然後按一下 [重新命名] 。將檔案名稱變更為 Bottom.aspx 。 4. 在 [檢視] 功能表上按一下 [HTML 原始檔] ,將下列 DataGrid 新增至
1<form> 和 </form>
標籤之間:
1<asp:datagrid backcolor="White" bordercolor="#999999" borderstyle="None" borderwidth="1px" cellpadding="3" font-names="Verdana" font-size="X-Small" gridlines="Vertical" height="100%" id="DataGrid1" runat="server" width="100%">
2<selecteditemstyle backcolor="#008A8C" font-bold="True" forecolor="White"></selecteditemstyle>
3<alternatingitemstyle backcolor="Gainsboro"></alternatingitemstyle>
4<itemstyle backcolor="#EEEEEE" bordercolor="Black" borderstyle="Solid" borderwidth="2px" forecolor="Black"></itemstyle>
5<headerstyle backcolor="#000084" bordercolor="Black" borderstyle="Solid" borderwidth="2px" font-bold="True" forecolor="White" horizontalalign="Center"></headerstyle>
6<footerstyle backcolor="#CCCCCC" forecolor="Black"></footerstyle>
7<pagerstyle backcolor="#999999" forecolor="Black" horizontalalign="Center" mode="NumericPages"></pagerstyle>
8</asp:datagrid>
- 在 [檢視] 功能表上按一下 [設計] ,便可返回設計檢視。
DataGrid 出現在 WebForm 上。 6. 在 [檢視] 功能表上按一下 [程式碼] ,如此便可顯示 Web Form 後面的程式碼。將下列程式碼新增至 Page_Load 事件處理常式:
注意 您必須將 User ID
1<username> 和 password=<strong password=""> 變更為正確的值,才能執行這個程式碼。使用者帳戶必須有正確的權限,才能在資料庫上執行這個作業。
2
3 ' Create a connection and open it.
4 Dim objConn As New System.Data.SqlClient.SqlConnection("User ID=<username>;Password=<strong password="">;Initial Catalog=Northwind;Data Source=SQLServer;")
5 objConn.Open()
6
7 Dim strSQL As String
8 Dim objDataset As New DataSet()
9 Dim objAdapter As New System.Data.SqlClient.SqlDataAdapter()
10
11 ' Get all the customers from the USA.
12 strSQL = "Select * from customers where country='USA'"
13 objAdapter.SelectCommand = New System.Data.SqlClient.SqlCommand(strSQL, objConn)
14 ' Fill the dataset.
15 objAdapter.Fill(objDataset)
16 ' Create a new view.
17 Dim oView As New DataView(objDataset.Tables(0))
18 ' Set up the data grid and bind the data.
19 DataGrid1.DataSource = oView
20 DataGrid1.DataBind()
21
22 ' Verify if the page is to be displayed in Excel.
23 If Request.QueryString("bExcel") = "1" Then
24 ' Set the content type to Excel.
25 Response.ContentType = "application/vnd.ms-excel"
26 ' Remove the charset from the Content-Type header.
27 Response.Charset = ""
28 ' Turn off the view state.
29 Me.EnableViewState = False
30
31 Dim tw As New System.IO.StringWriter()
32 Dim hw As New System.Web.UI.HtmlTextWriter(tw)
33
34 ' Get the HTML for the control.
35 DataGrid1.RenderControl(hw)
36 ' Write the HTML back to the browser.
37 Response.Write(tw.ToString())
38 ' End the response.
39 Response.End()
40 End If
41
42
43**注意** :請將程式碼中的 SQLServer 取代為您的 SQL Server 名稱。如果您無法存取 Northwind 範例資料庫所在的 SQL Server,請將連線字串修改為使用 Microsoft Access 2002 範例 Northwind 資料庫:
44
45
46provider=microsoft.jet.oledb.4.0; data source=C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb
47
48如果您選取這個方法,請將 aforementioned 程式碼修改為使用 **OleDbClient** 命名空間 (而不使用 **SqlClient** 命名空間)。
49 7. 在 **[專案]** 功能表上,按一下 **[加入 HTML 網頁]** 。將網頁命名為 **Top.htm** ,然後按一下 **[開啟]** 。
50
51「設計」檢視中會出現 Top.htm。
52 8. 在 **[檢視]** 功能表上,按一下 **[HTML 原始檔]** 。將 HTML 原始檔視窗的內容取代為下列程式碼:
53
54 <html>
55<script language="vbscript">
56 Sub Button1_onclick
57
58 Select Case Select1.selectedIndex
59
60 Case 0 ' Use Automation.
61 Dim sHTML
62 sHTML = window.parent.frames("bottom").document.forms(0).children("DataGrid1").outerhtml
63 Dim oXL, oBook
64 Set oXL = CreateObject("Excel.Application")
65 Set oBook = oXL.Workbooks.Add
66 oBook.HTMLProject.HTMLProjectItems("Sheet1").Text = sHTML
67 oBook.HTMLProject.RefreshDocument
68 oXL.Visible = true
69 oXL.UserControl = true
70
71 Case 1 ' Use MIME Type (In a New Window).
72 window.open("bottom.aspx?bExcel=1")
73
74 Case 2 ' Use MIME Type (In the Frame).
75 window.parent.frames("bottom").navigate "bottom.aspx?bExcel=1"
76 End Select
77 End Sub
78 </script>
79<body>
80 Export to Excel Using:
81 <select id="Select1" name="Select1" size="1">
82<option selected="" value="0">Automation</option>
83<option value="1">MIME Type (In a New Window)</option>
84<option value="2">MIME Type (In the Frame)</option>
85</select>
86<input id="Button1" name="Button1" type="button" value="Go!"/>
87</body>
88</html>
89
90
91 9. 在 **[專案]** 功能表上,按一下 **[加入 HTML 網頁]** 。將網頁命名為 **Frameset.htm** ,然後按一下 **[開啟]** 。
92
93「設計」檢視中會開啟 Frameset.htm。
94 10. 在 **[檢視]** 功能表上,按一下 **[HTML 原始檔]** 。將 HTML 原始檔視窗的內容取代為下列程式碼:
95
96 <html>
97<frameset rows="10%,90%">
98<frame name="top" noresize="0" scrolling="no" src="top.htm"/>
99<frame name="bottom" noresize="0" scrolling="yes" src="bottom.aspx"/>
100</frameset>
101</html>
102
103
104 11. 在「方案總管」的 **[Frameset.htm]** 上按滑鼠右鍵,然後按一下 **[設定為起始頁]** 。
105 12. 在 **[建置]** 功能表上,按一下 **[建置方案]** 。
106
107
108
109### 試試看!
110
111 1. 在 **[偵錯]** 功能表上按一下 **[啟動但不偵錯]** ,執行應用程式。
112
113Web 瀏覽器開啟框架組後,框架下方的 **DataGrid** 顯示出 Northwind 資料庫的資料。
114 2. 在下拉清單中按一下 **[Automation]** ,再按 **[Go]** 。
115
116**DataGrid** 內容會顯示在 Microsoft Excel 應用程式視窗的瀏覽器外側。
117 3. 在下拉清單中按一下 **[MIME Type (In a New Window)]** ,再按 **[Go]** 。
118
119**DataGrid** 內容會顯示在新 Web 瀏覽器視窗的 Excel 中。
120
121**注意** :提示您開啟或儲存 Excel 檔案時,請按一下 **[開啟]** 。
122 4. 在下拉清單中按一下 **[MIME Type (In the Frame)]** ,再按 **[Go]** 。
123
124**DataGrid** 內容會顯示在 Web 瀏覽器 Excel 框架組的下框架中。
125
126**注意** :提示您開啟或儲存 Excel 檔案時,請按一下 **[開啟]** 。</strong></username></strong></username>