简体   繁体   English

在Excel VB中打开数据表

[英]Open DataTable in Excel VB

Ok, this is an interesting issue. 好的,这是一个有趣的问题。 I have been tasked with modifying an existing VB project. 我的任务是修改现有的VB项目。 Currently the user selected from a series of dropdowns to select a sql query and then run that query. 当前,用户从一系列下拉菜单中选择一个sql查询,然后运行该查询。 So the user selects and environment dropdown, the results of that dropdown populates the category dropdown. 因此,用户选择“环境”下拉列表,该下拉列表的结果将填充类别下拉列表。 Once the category is selected, they get a dropdown of available queries. 选择类别后,他们将获得可用查询的下拉列表。 Once they select a query and hit the "Run" button, they get a gridview with the results of the query. 选择查询并单击“运行”按钮后,他们将获得带有查询结果的表格视图。 Some of the query results are huge. 一些查询结果是巨大的。 The query I'm running as a test has 40 columns and 20,000 records. 我正在作为测试运行的查询具有40列和20,000条记录。 The query runs in less than 5 seconds but it takes over a minute to render the gridview. 查询运行时间不到5秒,但是渲染网格视图需要一分钟以上的时间。 Once the gridview is done rendering, the user has the option to export the results to Excel. 完成gridview的渲染后,用户可以选择将结果导出到Excel。 And by this, I mean the code opens an instance of Excel through gridview.RenderControl and displays the results in Excel. 通过这个,我的意思是代码通过gridview.RenderControl打开Excel的实例,并在Excel中显示结果。 The user doesn't want to save the excel file and then navigate to the file, they want it to open right from the webform they are using which is what the code does currently. 用户不想保存excel文件,然后导航到该文件,而是希望它从所使用的Web表单中直接打开,这是代码当前正在执行的操作。

However, the user doesn't care about the gridview. 但是,用户并不关心gridview。 They don't care if they see it at all. 他们根本不在乎是否看到它。 They want to just open Excel. 他们只想打开Excel。 So instead of using gridview.RenderControl, I want to open Excel and populate it with the DataTable (or DataSet) in memory. 因此,我不想使用gridview.RenderControl,而是要打开Excel并在内存中填充DataTable(或DataSet)。 Any thoughts on the best way to do that? 关于最佳方法的想法吗?

Here's how they are currently populating the gridview: Dim MyConnection As SqlConnection Dim MyCommand As SqlCommand Dim MyDataTable As DataTable Dim MyReader As SqlDataReader 它们当前如何填充gridview:Dim MyConnection为SqlConnection Dim MyCommand为SqlCommand Dim MyDataTable为DataTable Dim MyReader为SqlDataReader

        MyConnection = New SqlConnection()
        MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings(Connection).ConnectionString

        MyCommand = New SqlCommand()
        MyCommand.CommandText = Sqlquery
        MyCommand.CommandType = CommandType.Text
        MyCommand.Connection = MyConnection

        MyCommand.Connection.Open()
        MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)

        MyDataTable = New DataTable()
        MyDataTable.Load(MyReader)

        If (MyDataTable.Rows.Count > 0) Then
            QueryresultPanel.Visible = True
            gvLineItems.DataSource = MyDataTable
            gvLineItems.DataBind()
        End If

        MyDataTable.Dispose()
        MyCommand.Dispose()
        MyConnection.Dispose()

Here's how they're opening and populating the instance of Excel: 这是他们打开和填充Excel实例的方式:

     Protected Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click
        Response.Clear()
        Response.Buffer = True
        '
        ' Set the content type to Excel.
        ' 
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
        Response.Charset = ""
        Response.ContentType = "application/vnd.ms-excel"
        ' 
        ' Turn off the view state.
        ' 
        Me.EnableViewState = False
        Dim oStringWriter As New System.IO.StringWriter()
        Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
        ' 
        ' Get the HTML for the control.
        '
        gvLineItems.RenderControl(oHtmlTextWriter)
        ' 
        ' Write the HTML back to the browser.
        '
        Response.Write(oStringWriter.ToString())
        Response.[End]()
    End Sub

Obviously, there's no RenderControl for a DataTable or DataSet and can't figure out how to get this record set to render in an instance of Excel without saving it to a file first. 显然,没有针对DataTable或DataSet的RenderControl,并且在不先将其保存到文件中的情况下,无法弄清楚如何在Excel实例中呈现此记录集。

Alright, here's the solution I found (in case anyone is interested). 好的,这是我找到的解决方案(以防万一有人感兴趣)。 It's pretty simple actually. 实际上,这非常简单。 I just looped through the datatable and used StringWriter. 我只是遍历数据表并使用了StringWriter。

    Protected Sub WriteToExcelFile(dt As DataTable)
    Dim sw As StringWriter

    For Each datacol As DataColumn In dt.Columns
        sw.Write(datacol.ColumnName + vbTab)
    Next

    Dim row As DataRow
    For Each row In dt.Rows
        sw.Write(vbNewLine)
        Dim column As DataColumn
        For Each column In dt.Columns
            If Not row(column.ColumnName) Is Nothing Then
                sw.Write(row(column).ToString() + vbTab)
            Else
                sw.Write(String.Empty + vbTab)
            End If
        Next column
    Next row

    Response.Clear()
    Response.ContentType = "application/vnd.ms-excel"
    Response.AddHeader("Content-Disposition", "attachment;filename=DataTable.xls")
    Response.Output.Write(sw.ToString())
    Response.Flush()
    System.Web.HttpContext.Current.Response.Flush()
    System.Web.HttpContext.Current.Response.SuppressContent = True
    System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest()
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM