'VB.NET Export datagridview in text file (.txt) fixed length

I need your help. I need to export my data gridview to a fixed length text (.txt) file.

Thank you for your help

This is my code:

Imports System.Data.OleDb

Imports System.IO

Public Class Form1
    
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    OpenFileDialog1.Filter = "Excel|`*`.xls;`*`.xlsx"
    OpenFileDialog1.ShowDialog()`
    txtFileName.Text = OpenFileDialog1.FileName
    Dim filepath As String = txtFileName.Text
    Dim connstring As String = String.Empty
    If filepath.EndsWith(".xls") Then
        connstring = String.Format("Provider=Microsoft.Jet.Oledb.4.0;" & "Data Source = {0};Extended Properties='Excel 8.0;HDR=yes'", filepath)
    Else
        connstring = String.Format("Provider=Microsoft.Ace.Oledb.12.0;" & "Data Source = {0};Extended Properties='Excel 8.0;HDR=yes'", filepath)
    End If
    Dim conn As New OleDbConnection(connstring)
    conn.Open()
    cboSheet.DataSource = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
    cboSheet.DisplayMember = "Table_Name"
    cboSheet.ValueMember = "Table_Name"
    conn.Close()

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim filepath As String = txtFileName.Text
    Dim connstring As String = String.Empty
    If filepath.EndsWith(".xls") Then
        connstring = String.Format("Provider=Microsoft.Jet.Oledb.4.0;" & "Data Source = {0};Extended Properties='Excel 8.0;HDR=yes'", filepath)
    Else
        connstring = String.Format("Provider=Microsoft.Ace.Oledb.12.0;" & "Data Source = {0};Extended Properties='Excel 8.0;HDR=yes'", filepath)
    End If
    Dim cmd As New OleDbDataAdapter("Select * from[" & cboSheet.Text & "" & "]", connstring)
    cmd.TableMappings.Add("Table", "Table")
    Dim dt As New DataSet
    cmd.Fill(dt)
    dgProposte.DataSource = dt.Tables(0)
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

Dim writer As TextWriter = New StreamWriter("C:\Users\antonio\Desktop\Prova.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
            writer.Write(vbTab & DataGridView1.Rows(i).Cells(j).Value.ToString() & vbTab & "")
        Next

        writer.WriteLine("")

    Next
    writer.Close()
    MessageBox.Show("Dati Esportati")


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source