Outputting to a CSV

  • Thread starter Thread starter stopiamwarren
  • Start date Start date
S

stopiamwarren

Guest
Hello everyone,

I am trying to read a fix width file and output it to a csv file. I have the reading part working, but I am stuck on outputting to csv.

newfNam is the output file name, and it may or may not exist. I don't know how to handle it if it does, I want to overwrite it.

fPath is the path of the text file.

Where I have the ****Place holder, I want to output each currentField and a comma until I reach the end of the line where i want to put in a vbCrLf. But I want to read each line and make sure it doesn't contain a comma already, and if it does, I want to encase that field in double quotes, so excel doesn't explode when I try to open the csv.

I've tried using objWriter but I'm not sure I'm using it correctly. I've backed this code out to a point where I know it is parsing each field correctly.

Public Class Ripper
Public fPath As String = ""
Private fName As String
Public Sub New(ByVal fNam As String)
fPath = fNam
Dim newfNam As String

newfNam = fPath.Substring(0, fPath.Length - 4) & ".csv"
'MsgBox(newfNam)
'MsgBox(fPath)

Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(fPath)

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(25, 150, 50, 50, 50, 50, 25, 50, 25, 300, 161, 25, 25, 50, 25, 49, 50, 150, 5, 25, 25, 50, 242, 15, 750, 4, 3, 10, 11, 18, 1, 1, 1, 1, 1, 1, 1, 52, 1, 27, 1, 1, 45)
Dim currentRow As String()

While Not Reader.EndOfData

Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'MsgBox(currentField)
'******* Place Holder
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

End While

End Using

End Sub
End Class

Any help would be amazing. Thanks.

Continue reading...
 
Back
Top