如何在 ASP 上导出 DataGrid 中的数据。 NET WebForm 到 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 浏览器中应用安全设置。

分步

  1. 启动 Visual Studio .NET。 在"文件"菜单上,指向"新建",然后单击"项目"。

  2. 在“项目类型”窗格中,单击“Visual Basic 项目”。 在“模板”下,单击 ASP.NET Web 应用程序。 将应用程序命名为 ExcelExport,然后单击“确定”。

    WebForm1 显示在设计视图中。

  3. 在解决方案资源管理器中,右键单击 WebForm1.aspx,然后单击“重命名”。 将文件的名称更改为 Bottom.aspx。

  4. 在“视图”菜单上,单击“HTML 源”,在 “视图”之间添加以下 DataGrid

    标签:

    <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>
    
    
  5. 在“视图”菜单上,单击“设计”返回到设计视图。

    DataGrid 显示在 WebForm 上。

  6. 在“视图”菜单上,单击“代码”以显示 Web 窗体后面的代码。 将以下代码添加到Page_Load事件处理程序:

    注意 运行此代码之前,必须将用户 ID <用户名> 和密码=<强密码> 更改为正确的值。 确保用户帐户具有对数据库执行此操作的正确权限。

    ' 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

    如果选择此方法,请修改上述代码以使用 OleDbClient 命名空间,而不是 SqlClient 命名空间。

  7. 在“项目”菜单上,单击“添加 HTML 页”。 将页面命名为Top.htm,然后单击“打开”。

    Top.htm显示在“设计”视图中。

  8. 在“视图”菜单上,单击“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>
    
    
  9. 在“项目”菜单上,单击“添加 HTML 页”。 将页面命名为Frameset.htm,然后单击“打开”。

    Frameset.htm在“设计”视图中打开。

  10. 在“视图”菜单上,单击“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>
    
    
  11. 在解决方案资源管理器中,右键单击Frameset.htm,然后单击“设置为开始页”。

  12. 在"构建"菜单上,单击"构建解决方案"。

试试!

  1. 在“调试”菜单上,单击“开始而不调试”以运行应用程序。

    在 Web 浏览器中打开帧集后,底部帧中的 DataGrid 将显示来自 Northwind 数据库的数据。

  2. 在下拉列表中,单击“自动化”,然后单击“Go”。

    DataGrid 内容显示在 Microsoft Excel 应用程序窗口的浏览器外部。

  3. 在下拉列表中,单击 “新建窗口”) (MIME 类型 ,然后单击“Go”。

    DataGrid 内容显示在新的 Web 浏览器窗口中托管的 Excel 中。

    注意 如果收到打开或保存 Excel 文件的提示,请单击“打开”。

  4. 在下拉列表中,单击 “框架) ”中的 MIME 类型 ( ,然后单击“Go”。

    DataGrid 内容显示在 Web 浏览器中托管的 Excel 中帧集的底部框架中。

    注意 如果收到打开或保存 Excel 文件的提示,请单击“打开”。

参考

有关其他信息,请查看 Microsoft 知识库中的文章:

296717 PRB:Internet Explorer 提示用户打开/保存从 ASP 流式传输的 Office 文件