將 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。 - 在「方案總管」的 [WebForm1.aspx] 上按右滑鼠鍵,然後按一下 [重新命名]。將檔案名稱變更為 Bottom.aspx。
- 在 [檢視] 功能表上按一下 [HTML 原始檔],將下列 DataGrid 新增至 <form> 和 </form> 標籤之間:
<asp:datagrid id="DataGrid1" runat="server" GridLines="Vertical" CellPadding="3" BackColor="White" BorderColor="#999999" BorderWidth="1px" BorderStyle="None" Width="100%" Height="100%" Font-Size="X-Small" Font-Names="Verdana"> <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#008A8C"></SelectedItemStyle> <AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle> <ItemStyle BorderWidth="2px" ForeColor="Black" BorderStyle="Solid" BorderColor="Black" BackColor="#EEEEEE"></ItemStyle> <HeaderStyle Font-Bold="True" HorizontalAlign="Center" BorderWidth="2px" ForeColor="White" BorderStyle="Solid" BorderColor="Black" BackColor="#000084"></HeaderStyle> <FooterStyle ForeColor="Black" BackColor="#CCCCCC"></FooterStyle> <PagerStyle HorizontalAlign="Center" ForeColor="Black" BackColor="#999999" Mode="NumericPages"></PagerStyle> </asp:datagrid>
- 在 [檢視] 功能表上按一下 [設計],便可返回設計檢視。
DataGrid 出現在 WebForm 上。 - 在 [檢視] 功能表上按一下 [程式碼],如此便可顯示 Web Form 後面的程式碼。將下列程式碼新增至 Page_Load 事件處理常式:
注意您必須將 User ID <username> 和 password=<strong password> 變更為正確的值,才能執行這個程式碼。使用者帳戶必須有正確的權限,才能在資料庫上執行這個作業。' Create a connection and open it. Dim objConn As New System.Data.SqlClient.SqlConnection("User ID=<username>;Password=<strong password>;Initial Catalog=Northwind;Data Source=SQLServer;") objConn.Open() Dim strSQL As String Dim objDataset As New DataSet() Dim objAdapter As New System.Data.SqlClient.SqlDataAdapter() ' Get all the customers from the USA. strSQL = "Select * from customers where country='USA'" objAdapter.SelectCommand = New System.Data.SqlClient.SqlCommand(strSQL, objConn) ' Fill the dataset. objAdapter.Fill(objDataset) ' Create a new view. Dim oView As New DataView(objDataset.Tables(0)) ' Set up the data grid and bind the data. DataGrid1.DataSource = oView DataGrid1.DataBind() ' Verify if the page is to be displayed in Excel. If Request.QueryString("bExcel") = "1" Then ' Set the content type to Excel. Response.ContentType = "application/vnd.ms-excel" ' Remove the charset from the Content-Type header. Response.Charset = "" ' Turn off the view state. Me.EnableViewState = False Dim tw As New System.IO.StringWriter() Dim hw As New System.Web.UI.HtmlTextWriter(tw) ' Get the HTML for the control. DataGrid1.RenderControl(hw) ' Write the HTML back to the browser. Response.Write(tw.ToString()) ' End the response. Response.End() End If
注意:請將程式碼中的 SQLServer 取代為您的 SQL Server 名稱。如果您無法存取 Northwind 範例資料庫所在的 SQL Server,請將連線字串修改為使用 Microsoft Access 2002 範例 Northwind 資料庫:
provider=microsoft.jet.oledb.4.0; data source=C:/Program Files/Microsoft Office/Office10/Samples/Northwind.mdb
如果您選取這個方法,請將 aforementioned 程式碼修改為使用 OleDbClient 命名空間 (而不使用 SqlClient 命名空間)。 - 在 [專案] 功能表上,按一下 [加入 HTML 網頁]。將網頁命名為 Top.htm,然後按一下 [開啟]。
「設計」檢視中會出現 Top.htm。 - 在 [檢視] 功能表上,按一下 [HTML 原始檔]。將 HTML 原始檔視窗的內容取代為下列程式碼:
<html> <script language="vbscript"> Sub Button1_onclick Select Case Select1.selectedIndex Case 0 ' Use Automation. Dim sHTML sHTML = window.parent.frames("bottom").document.forms(0).children("DataGrid1").outerhtml Dim oXL, oBook Set oXL = CreateObject("Excel.Application") Set oBook = oXL.Workbooks.Add oBook.HTMLProject.HTMLProjectItems("Sheet1").Text = sHTML oBook.HTMLProject.RefreshDocument oXL.Visible = true oXL.UserControl = true Case 1 ' Use MIME Type (In a New Window). window.open("bottom.aspx?bExcel=1") Case 2 ' Use MIME Type (In the Frame). window.parent.frames("bottom").navigate "bottom.aspx?bExcel=1" End Select End Sub </script> <body> Export to Excel Using: <SELECT id="Select1" size="1" name="Select1"> <OPTION value="0" selected>Automation</OPTION> <OPTION value="1">MIME Type (In a New Window)</OPTION> <OPTION value="2">MIME Type (In the Frame)</OPTION> </SELECT> <INPUT id="Button1" type="button" value="Go!" name="Button1"> </body> </html>
- 在 [專案] 功能表上,按一下 [加入 HTML 網頁]。將網頁命名為 Frameset.htm,然後按一下 [開啟]。
「設計」檢視中會開啟 Frameset.htm。 - 在 [檢視] 功能表上,按一下 [HTML 原始檔]。將 HTML 原始檔視窗的內容取代為下列程式碼:
<html> <frameset rows="10%,90%"> <frame noresize="0" scrolling="no" name="top" src="top.htm"> <frame noresize="0" scrolling="yes" name="bottom" src="bottom.aspx"> </frameset> </html>
- 在「方案總管」的 [Frameset.htm] 上按滑鼠右鍵,然後按一下 [設定為起始頁]。
- 在 [建置] 功能表上,按一下 [建置方案]。
試試看!
- 在 [偵錯] 功能表上按一下 [啟動但不偵錯],執行應用程式。
Web 瀏覽器開啟框架組後,框架下方的 DataGrid 顯示出 Northwind 資料庫的資料。 - 在下拉清單中按一下 [Automation],再按 [Go]。
DataGrid 內容會顯示在 Microsoft Excel 應用程式視窗的瀏覽器外側。 - 在下拉清單中按一下 [MIME Type (In a New Window)],再按 [Go]。
DataGrid 內容會顯示在新 Web 瀏覽器視窗的 Excel 中。
注意:提示您開啟或儲存 Excel 檔案時,請按一下 [開啟]。 - 在下拉清單中按一下 [MIME Type (In the Frame)],再按 [Go]。
DataGrid 內容會顯示在 Web 瀏覽器 Excel 框架組的下框架中。
注意:提示您開啟或儲存 Excel 檔案時,請按一下 [開啟]。