【问题标题】:Download xls file to client from Datatable从 Datatable 下载 xls 文件到客户端
【发布时间】:2017-09-06 02:40:05
【问题描述】:

我正在使用 VB 在 VisualStudio 上开发一个网站。在我网站的一个部分中,我进行了数据库查询,将结果存储在 DataTable 中并显示出来。我为用户提供了下载信息的选项,我想做的是使用数据表中的信息将 XLS 文件下载到客户端,而无需在服务器端创建 xls。

我目前有以下代码部分可以将文件发送给用户

Dim fileToDownload = Server.MapPath("~/docs/QuejometroVF.pdf")
Response.ContentType = "application/octet-stream"

Dim cd = New ContentDisposition()
cd.Inline = False
cd.FileName = Path.GetFileName(fileToDownload)
Response.AppendHeader("Content-Disposition", cd.ToString())

Dim fileData = System.IO.File.ReadAllBytes(fileToDownload)
Response.OutputStream.Write(fileData, 0, fileData.Length)

但它需要一个本地文件的路径才能发送它。

首先我想知道如何从数据表(仅在内存中)创建一个 xls 文件,然后将该对象作为文件发送到客户端的计算机。如果不可能,你能告诉我如何在我的服务器中编写 xls 文件,以便我可以使用上面的代码发送它吗?我还没有真正弄清楚该怎么做。

我正在考虑这样做,因为当我已经在数据库中拥有该信息并且我不假装保存该文件时,我不想将文件保留在服务器中。

谢谢

【问题讨论】:

    标签: excel vb.net datatable


    【解决方案1】:

    我使用以下代码将数据导出到 xls 文件,我的后端是一个 Oracle 数据库,这就是我获取数据的地方:

        Dim MyConnection As OracleConnection = OpenConnection(Session("USERNAME"), Session("PASSWORD"))
        Dim MyDataSet As New DataSet
        MyDataSet = GetExportData(MyConnection, Session("UserDataKey"), Session("CompoundKey"), Session("LastOfCompoundKey"))
    
        'I rename the dataset's table columns to what I want in the xls file
        MyDataSet.Tables!data.Columns(0).ColumnName = "IDNumber"
        MyDataSet.Tables!data.Columns(1).ColumnName = "FirstName"
        MyDataSet.Tables!data.Columns(2).ColumnName = "LastName"
        MyDataSet.Tables!data.Columns(3).ColumnName = "Address"
        MyDataSet.Tables!data.Columns(4).ColumnName = "City"
        MyDataSet.Tables!data.Columns(5).ColumnName = "State"
        MyDataSet.Tables!data.Columns(6).ColumnName = "ZipCode"
        MyDataSet.Tables!data.Columns(7).ColumnName = "Phone_Area"
        MyDataSet.Tables!data.Columns(8).ColumnName = "Phone_Prefix"
        MyDataSet.Tables!data.Columns(9).ColumnName = "Phone_Suffix"
        MyDataSet.Tables!data.Columns(10).ColumnName = "Email"
        MyDataSet.Tables!data.Columns(11).ColumnName = "BirthDay"
    
        Response.ClearContent()
    
        'I create the filename I want the data to be saved to and set up the response
        Response.AddHeader("content-disposition", "attachment; filename=" & Replace(Session("Key0"), " ", "-") & "-" & Session("Key1") & "-" & Replace(Replace(Trim(Session("Key2")), ".", ""), " ", "-") & ".xls")
    
        Response.ContentType = "application/excel"
    
        Response.Charset = ""
    
        EnableViewState = False
    
        Dim tw As New System.IO.StringWriter
    
        Dim hw As New System.Web.UI.HtmlTextWriter(tw)
    
        'Create and bind table to a datagrid
        Dim dgTableForExport As New DataGrid
    
        If MyDataSet.Tables.Count > 0 Then
            If MyDataSet.Tables(0).Rows.Count > 0 Then
                dgTableForExport.DataSource = MyDataSet.Tables(0) ' .DefaultView
                dgTableForExport.DataBind()
    
                'Finish building response
                Dim strStyle As String = "<style>.text { mso-number-format:\@; } </style>"
                For intTemp As Integer = 0 To MyDataSet.Tables(0).Rows.Count - 1
                    For intTemp2 As Integer = 0 To MyDataSet.Tables(0).Columns.Count - 1
                        dgTableForExport.Items(intTemp).Cells(intTemp2).Attributes.Add("class", "text")
                    Next
                Next
            End If
        End If
    
    
        dgTableForExport.RenderControl(hw)
        Response.Write(style)
        ' Write the HTML back to the browser.                         
    
        Response.Write(tw.ToString())
        Response.End()
    
        'Close, clear and dispose
        MyConnection.Close()
        MyConnection.Dispose()
        MyConnection = Nothing
    

    我从我的一个项目中复制并粘贴了此内容,它未经测试,可能包含错误,但应该可以帮助您入门。

    【讨论】:

      【解决方案2】:

      您可以使用MemoryStream 或使用Response.Write 方法将文件写入响应流。

      【讨论】:

        【解决方案3】:

        从数据表创建 excel 文件相当容易,因为您只需创建一个 GridView 并将表绑定到它。

        这里有一个代码 sn-p 可以满足您的需要。

        Public Sub DownloadExcel(outputTable as System.Data.DataTable)
            Dim gv As New GridView
            Dim tw As New StringWriter
            Dim hw As New HtmlTextWriter(tw) 
            Dim sheetName As String = "OutputFilenameHere"
        
            gv.DataSource = outputTable
            gv.DataBind()
            gv.RenderControl(hw)
            Response.AddHeader("content-disposition", "attachment; filename=" & sheetName & ".xls")
            Response.ContentType = "application/octet-stream"
            Response.Charset = ""
            EnableViewState = False
            Response.Write(tw.ToString)
            Response.End()
        End Sub
        

        这个方法有几个问题:

        1. 这不会输出本机 excel 文件。相反,它会输出 Excel 将检测到的 GridView 的 HTML,并通知用户内容与扩展名不匹配。但是,如果用户从对话框中选择“是”,它将在 Excel 中正确显示。

        2. 早期版本的 Firefox 和 Chrome 不喜欢这种方法,而是下载扩展名为 .html 的文件。我刚刚在两种浏览器中都对其进行了测试,并且它适用于最新版本。

        理想情况下,您应该在您的网络服务器上使用 Excel 来创建本地电子表格,但如果您(像我一样)没有办法这样做,这将起作用。

        【讨论】:

          猜你喜欢
          • 2022-07-21
          • 1970-01-01
          • 2023-04-01
          • 2019-03-04
          • 2012-11-17
          • 1970-01-01
          • 2022-01-13
          • 1970-01-01
          相关资源
          最近更新 更多