Exporting Text File using VB. net

soLo Lz 41 Reputation points
2023-01-10T01:35:32.317+00:00

Good day, I would like to ask on how to arrange the exported text file. Below, I have the code using vb. net and the result of file exported.

Dim writer As New StreamWriter("D:\PDAexport.txt")

    For i As Integer = 0 To dataGridView1.Rows.Count - 2 Step +1  

        For j As Integer = 0 To dataGridView1.Columns.Count - 1 Step +1  

            If j = dataGridView1.Columns.Count - 1 Then  

                writer.Write(vbTab & dataGridView1.Rows(i).Cells(j).Value.ToString())  

            Else  
                writer.Write(vbTab & dataGridView1.Rows(i).Cells(j).Value.ToString() & vbTab & "|")  

            End If  
        Next j  

        writer.WriteLine("")  

    Next i  

    writer.WriteLine("")  
    MessageBox.Show("Data Exported")  

Result :

277701-result.jpg

Should be Arrange like this:

277655-looklikethis.jpg

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,641 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 26,751 Reputation points Microsoft Vendor
    2023-01-10T07:01:10.227+00:00

    Hi @soLo Lz , You need to fill the data in each column with spaces to the same length. You can refer to the following code to modify the value of columnLengths to fit your data.

        Enum JustifyType
            LEFT
            RIGHT
            CENTER
        End Enum
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim writer As New StreamWriter("C:\Users\Administrator\Desktop\PDAexport.txt")
            Dim textToOutput = ""
            Dim numCols As Integer = DataGridView1.ColumnCount
            Dim numRows As Integer = DataGridView1.RowCount - 1
            Dim columnLengths As Int16() = {6, 32, 12, 16}
            For i As Integer = 0 To DataGridView1.Rows.Count - 2 Step +1
                For j As Integer = 0 To DataGridView1.Columns.Count - 1 Step +1
                    Console.WriteLine(DataGridView1.Rows(i).Cells(j).Value.ToString())
                    textToOutput = GetBufferedString(DataGridView1.Rows(i).Cells(j).Value, columnLengths(j), JustifyType.LEFT)
    
                    If j = DataGridView1.Columns.Count - 1 Then
    
                        writer.Write(vbTab & textToOutput)
                    Else
                        writer.Write(vbTab & textToOutput & vbTab & "|")
                    End If
                Next j
                writer.WriteLine("")
            Next i
            writer.WriteLine("")
            writer.Close()
            MessageBox.Show("Data Exported")
        End Sub
    
        Private Function GetBufferedString(originalString As String, maxLength As Int16, justifyType As JustifyType) As String
            If (originalString.Length < maxLength) Then
                Dim bufString = Space(maxLength - originalString.Length)
                Select Case justifyType
                    Case JustifyType.LEFT
                        Return originalString + bufString
                    Case JustifyType.RIGHT
                        Return bufString + originalString
                    Case JustifyType.CENTER
                        Dim halfString = bufString.Substring(bufString.Length / 2)
                        originalString = halfString + originalString
                        bufString = Space(maxLength - originalString.Length)
                        Return originalString + bufString
                    Case Else
                        Return ""
                End Select
            Else
                Return originalString.Substring(0, maxLength)
            End If
        End Function
    

    Best Regards. Jiachen Li

    If the answer is helpful, please click "Accept Answer" and upvote it. Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


3 additional answers

Sort by: Most helpful
  1. LesHay 7,126 Reputation points
    2023-01-11T17:41:44.2733333+00:00

    Hi

    I tried to add an image to my original Answer posted in this thread, but the 'New' forum didn;t like it and deleted the entire post - so here it is again!

    
    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        ' FORM1 has a DataGridView1 on it
        ' with 3 columns (0,1 and 2)
    
        ' this ONLY to generate some
        ' random data for example
        Dim r As New Random
        Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        For i As Integer = 0 To 5
          Dim nr(2) As String
          For c As Integer = 0 To 2
            Dim r1 As Integer = r.Next(4, 8)
            Dim s1 As String = s.Substring(r.Next(25 - r1), r1)
            nr(c) = s1
          Next
          DataGridView1.Rows.Add(nr)
        Next
    
        ' this section ONLY for the format
        ' of the export
        Dim MyPath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "PDAexport.txt")
        Using writer As New IO.StreamWriter(MyPath, False)
          For i As Integer = 0 To DataGridView1.Rows.Count - 2
            For j As Integer = 0 To DataGridView1.Columns.Count - 1
              With DataGridView1
                If j = DataGridView1.Columns.Count - 1 Then
                  writer.WriteLine(DataGridView1.Rows(i).Cells(j).Value.ToString.PadRight(12))
                Else
                  writer.Write(DataGridView1.Rows(i).Cells(j).Value.ToString.PadRight(12) & "|".PadRight(4))
                End If
              End With
            Next
          Next
        End Using
      End Sub
    End Class
    
    
    1 person found this answer helpful.
    0 comments No comments

  2. LesHay 7,126 Reputation points
    2023-01-10T07:19:27.617+00:00

    Hi You could have included a section of data for us to use to illustrate possible solutions. Since you didn't include any data, here are a couple of suggestions using some random data. The way to format the export is shown. Try this code as a new TEST PROJECT.

    ![277620-111.png][1]=========================================================

    EDIT: this new forum has seen fit to corrupt posted code. If you use the Copy button and paste into your own project,

    111

    =========================================================

        ' FORM1 has a DataGridView1 on it
        ' with 3 columns (0,1 and 2)
    
        ' this ONLY to generate some
        ' random data for example
        Dim r As New Random
        Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        For i As Integer = 0 To 5
          Dim nr(2) As String
          For c As Integer = 0 To 2
            Dim r1 As Integer = r.Next(4, 8)
            Dim s1 As String = s.Substring(r.Next(25 - r1), r1)
            nr(c) = s1
          Next
          DataGridView1.Rows.Add(nr)
        Next
    
        ' this section ONLY for the format
        ' of the export
        Dim MyPath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "PDAexport.txt")
        Using writer As New StreamWriter(MyPath, False)
          For i As Integer = 0 To DataGridView1.Rows.Count - 2
            For j As Integer = 0 To DataGridView1.Columns.Count - 1
              With DataGridView1
                If j = DataGridView1.Columns.Count - 1 Then
                  writer.WriteLine(DataGridView1.Rows(i).Cells(j).Value.ToString.PadRight(12))
                Else
                  writer.Write(DataGridView1.Rows(i).Cells(j).Value.ToString.PadRight(12) & "|".PadRight(4))
                End If
              End With
            Next
          Next
        End Using
    
    0 comments No comments

  3. Dewayne Basnett 1,116 Reputation points
    2023-01-10T16:01:44.213+00:00

    This assumes that the DGV columns are displaying all of the data i.e. DataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            Dim sb As New System.Text.StringBuilder
            Dim chkCH As Char = " "c  ' ChrW(&H8195) 'em space
            Dim width As Integer
            Using g As Graphics = DataGridView1.CreateGraphics
                width = CInt(g.MeasureString(chkCH, DataGridView1.Font).Width)
            End Using
            For rwidx As Integer = 0 To DataGridView1.Rows.Count - 2
                For colidx As Integer = 0 To DataGridView1.Columns.Count - 1
                    sb.Append(DataGridView1.Rows(rwidx).Cells(colidx).Value.ToString.PadRight(DataGridView1.Columns(colidx).Width \ width + 1))
                    If colidx <> DataGridView1.Columns.Count - 1 Then
                        sb.Append(ControlChars.Tab)
                        sb.Append(" | ")
                    End If
                Next colidx
                sb.AppendLine()
            Next rwidx
            Dim path As String = "D:\PDAexport.txt"
            IO.File.WriteAllText(path, sb.ToString)
    
    0 comments No comments