Generate Text File from Stored Procedure Using VB.Net

Here's how I generate text file from a 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")

            WriteToText(resTable, strpath)
         
        Catch ex As Exception

        End Try
  End Sub


#Region "ToText"
    Private Shared Sub WriteToText(dt As DataTable, outputFilePath As String)
        Dim maxLengths As Integer() = New Integer(dt.Columns.Count - 1) {}

        For i As Integer = 0 To dt.Columns.Count - 1
            maxLengths(i) = dt.Columns(i).ColumnName.Length

            For Each row As DataRow In dt.Rows
                If Not row.IsNull(i) Then
                    Dim length As Integer = row(i).ToString().Length

                    If length > maxLengths(i) Then
                        maxLengths(i) = length
                    End If
                End If
            Next
        Next

        Using sw As New StreamWriter(outputFilePath, False)
            For i As Integer = 0 To dt.Columns.Count - 1
                sw.Write(dt.Columns(i).ColumnName.PadRight(maxLengths(i) + 2))
            Next

            sw.WriteLine()

            For Each row As DataRow In dt.Rows
                For i As Integer = 0 To dt.Columns.Count - 1
                    If Not row.IsNull(i) Then
                        sw.Write(row(i).ToString().PadRight(maxLengths(i) + 2))
                    Else
                        sw.Write(New String(" "c, maxLengths(i) + 2))
                    End If
                Next

                sw.WriteLine()
            Next

            sw.Close()
        End Using
    End Sub
#End Region


No comments:

Post a Comment