在调试模式下成功导出到csv,但在运行时模式下失败

时间:2019-07-09 23:17:40

标签: sql sql-server vb.net csv

我正在将记录从SQL Server表读取到数据集中,然后将其导出到CSV文件。当我在调试模式下逐步执行时,一切正常。当我运行它时,它仅导出一个包含废话数据的单元格。由于它是ASP.NET应用程序,所以我不确定在回发方面是否做错了什么。似乎在运行时,它并不等待CSV文件被写入。

Dim sbldRecordCSV As New StringBuilder

Dim dtHCMTable As DataTable = mdsHCMTable.Tables(0)
Dim intIndex As Integer = 0

'Read the connection-string from web.config
Dim connHCM As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("connHCM").ConnectionString)

'Read the exported CSV file path from web.config
Dim strCSVpath As String = System.Configuration.ConfigurationManager.AppSettings("CSVpath").ToString

Try
    For intIndex = 0 To mdsHCMTable.Tables(0).Rows.Count - 1
        Dim drHCMTable As DataRow = dtHCMTable.Rows(intIndex)
        For Each field As Object In drHCMTable.ItemArray
            sbldRecordCSV.Append(field.ToString & "|")
        Next
        sbldRecordCSV.Replace("|", vbNewLine, sbldRecordCSV.Length - 1, 1)
    Next

    My.Computer.FileSystem.WriteAllText(strCSVpath.ToString & lstDataTables.SelectedValue.ToString & ".csv", sbldRecordCSV.ToString, False)

1 个答案:

答案 0 :(得分:0)

经过一番搜索,我意识到我需要修改ExportCSV代码。修改后的例程如下:

受保护的子ExportToCSV(mdsHCMTable作为数据集)         Dim dt As DataTable = mdsHCMTable.Tables(0)

    'Read the exported CSV file path from web.config
    Dim strCSVpath As String = System.Configuration.ConfigurationManager.AppSettings("CSVpath").ToString

    Response.Clear()
    Response.Buffer = True
    Response.AddHeader("content-disposition", "attachment;filename=" & lstDataTables.SelectedValue.ToString & ".csv")
    Response.Charset = ""
    Response.ContentType = "application/text"

    Dim sb As New StringBuilder()
    For k As Integer = 0 To dt.Columns.Count - 1
        'add separator
        sb.Append(dt.Columns(k).ColumnName + "|"c)
    Next
    'append new line
    sb.Append(vbCr & vbLf)
    For i As Integer = 0 To dt.Rows.Count - 1
        For k As Integer = 0 To dt.Columns.Count - 1
            'add separator
            sb.Append(dt.Rows(i)(k).ToString().Replace(",", "|") + "|"c)
        Next
        'append new line
        sb.Append(vbCr & vbLf)
    Next

    Response.Clear()
    Response.BufferOutput = False
    Response.Output.Write(sb.ToString())
    Response.Flush()
End Sub

此解决方案对我有用。希望对其他人有帮助。