Generate CSV File from Stored Procedure using VB.Net

Here's how I generate CSV File from Stored Procedure

Public Sub GetDataFromStored()
        Try
            Dim cmd As SqlCommand = New SqlCommand
            Dim strpath As String = Application.StartupPath + "\Result.txt"
  
            con.ConnectionString = strCon
            cmd.Connection = con
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "StoredProcedureName"

            pagingAdapter = New SqlDataAdapter(cmd)
            pagingDS = New DataSet()

            con.Open()
            pagingAdapter.Fill(pagingDS, scrollVal, pagingDS.Tables.Count, "StoredProcedureName")
            con.Close()

            Dim resTable As DataTable = pagingDS.Tables("StoredProcedureName")

            WriteToCSV(resTable, strpath)
          
        Catch ex As Exception

        End Try
  End Sub

#Region "CSV"

    Sub WriteToCSV(dt As DataTable, path As String)

        Dim str As New StringBuilder

        For Each dr As DataRow In dt.Rows
            For Each field As Object In dr.ItemArray
                str.Append(field.ToString & ",")
            Next
            str.Replace(",", vbNewLine, str.Length - 1, 1)
        Next

        Try
            My.Computer.FileSystem.WriteAllText(path, str.ToString, False)
        Catch ex As Exception
            MessageBox.Show("Write Error")
        End Try

    End Sub

#End Region

No comments:

Post a Comment