DataTable到文件

时间:2015-04-07 16:56:49

标签: vb.net

Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String)
DataTable2CSV(table, filename, vbTab)
End Sub

Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String, _
ByVal sepChar As String)
Dim writer As System.IO.StreamWriter
Try
    writer = New System.IO.StreamWriter(filename)

    ' first write a line with the columns name
    Dim sep As String = ""
    Dim builder As New System.Text.StringBuilder
    For Each col As DataColumn In table.Columns
        builder.Append(sep).Append(col.ColumnName)
        sep = sepChar
    Next
    writer.WriteLine(builder.ToString())

    ' then write all the rows
    For Each row As DataRow In table.Rows
        sep = ""
        builder = New System.Text.StringBuilder

        For Each col As DataColumn In table.Columns
            builder.Append(sep).Append(row(col.ColumnName))
            sep = sepChar
        Next
        writer.WriteLine(builder.ToString())
    Next
Finally
    If Not writer Is Nothing Then writer.Close()
End Try
End Sub

我在搜索“DataTable to File VB.net”后在互联网上找到了这段代码。我想要做的是在文件流中输出,是否可以设置响应输出流?感谢

编辑:澄清(改变)以下是我现在正在使用的内容:

    Protected Sub DoExportFinancials()
    Dim ef As New ExportFinancials()
    ef.Behavior = ExportFinancials.ObjectBehavior.Export
    If ef.Load() = True Then

        Me.GridView4.DataSource = ef.DT
        Me.GridView4.DataBind()

        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
        ' Response.Charset = ""
        'Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Dim stringWrite As StringWriter = New StringWriter
        Dim htmlWrite As HtmlTextWriter = New HtmlTextWriter(stringWrite)
        GridView4.RenderControl(htmlWrite)
        Response.Write(stringWrite.ToString())
        Response.End()

    End If

1 个答案:

答案 0 :(得分:1)

以下内容应该有效,

    Dim FilePath As String = serverPath & "\App_Data\" & FileName
    Response.Clear()
    Response.ContentType = "text/csv"
    Response.AddHeader("Content-Disposition", "attachment; filename=" & FileName)
    Response.TransmitFile(FilePath)
    Response.End()

编辑:根据问题的更多细节, [更改]:如何将DataTable作为CSV / Excel文件传递给Response Stream,而不将其写入服务器上的磁盘。

实现上述目标的一种方法是首先将DataTable绑定到GridView,然后使用下面的方法将GridView的内容传递给响应流,

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = "" Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim stringWrite As StringWriter = New StringWriter
Dim htmlWrite As HtmlTextWriter = New HtmlTextWriter(stringWrite)
grid.RenderControl(htmlWrite) Response.Write(stringWrite.ToString())
Response.End()