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.