Link to home
Start Free TrialLog in
Avatar of Denny Farrell
Denny FarrellFlag for United States of America

asked on

editing CSV file in VB. Visual Studio 2010 used.

I have a CSV file that looks like this:
a,b,c,d,e,f
1,2,3,4,5,6

Can anyone help me figure out a way to eliminate Nth(lets say 4th) column from every line in VB?

I found a way to parse it online which looks like this:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\test.csv")
            MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
            'set the delimiter to any value
            MyReader.Delimiters = New String() {","}

            Dim currentRow As String()

            'Loop through all of the fields in the file.
            'If any lines are corrupt, report an error and continue parsing.
            While Not MyReader.EndOfData
                Try
                    currentRow = MyReader.ReadFields()
                    'ouput the second value of each line to show that the file has been parsed.
                    currentRow(4)

                    MsgBox(currentRow(4))
                                   Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                    MsgBox("Line " & ex.Message & _
                    " is invalid. Skipping")
                End Try

            End While

        End Using

    End Sub

--------------------------

Works pretty well, however, I need to not show this value, but DELETE it.

thank you,
Avatar of Athar Syed
Athar Syed
Flag of Kuwait image

An long but easier way would be to populate a dataset object and then delete the column fron the file and then resave the data back to csv.
Declare your string builder BEFORE the using statement
        Dim sBuilder As New System.Text.StringBuilder

Then in the try ..catch build up your string
        Try
            currentRow = MyReader.ReadFields()
            sBuilder.Append(currentRow(1) & "," & currentRow(2) & "," & currentRow(3) & "," & currentRow(5) & vbCrLf)
        Catch ex As Exception

        End Try

As suggested, delete the old file then resave it. I would prefer saving the new file to a different name!

        System.IO.File.Delete("C:\test.csv")
        System.IO.File.WriteAllText("C:\test.csv", sBuilder.ToString)
Avatar of Mike Tomlinson
Here's another approach:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim FileName As String = "c:\some\file.txt"
        Dim lines() As String = System.IO.File.ReadAllLines(FileName)
        Dim values As New List(Of String)
        For i As Integer = 0 To lines.GetUpperBound(0)
            values.Clear()
            values.AddRange(lines(i).Split(","))
            values.RemoveAt(3) ' Rmove 4th column
            lines(i) = String.Join(",", values.ToArray)
        Next
        System.IO.File.WriteAllLines(FileName, lines)
    End Sub

Open in new window

Avatar of Denny Farrell

ASKER

The real worksheet has 60 columns, therefore, manually typing them all out in the script would be a LOT of work. I will try Idle_mind's case and see how it works tomorrow morning...
Idle mind,
the code work great.
My last question would be: what would be a proper programming way to delete 3 columns instead of one. i tried to run 3 consecutive FOR statemenet deleting one column at a time because it wasn't deleting properly after going through the first three lines of numbers. however, that didn't help the issue either.
I need to delete columns 100, 88, and 85 to make format look the same.

I have attached 2 actual files that I am trying to match so that you everyone could understand exactly what I am talking about.

I need the columns of TEST.CSV to match the columns of BEEZLEY.CSV in order for newly generated CSVs to import properly in my design program.

thank you
test.csv
BEEZLEY-STEWART-ENTRY.csv
This is what I have. I start from the last column in order to avoid shifting columns to the right BEFORE deleting other columnt to the right if that makes sense.

 Dim FileName As String = "c:\test.csv"
        Dim lines() As String = System.IO.File.ReadAllLines(FileName)
        Dim values As New List(Of String)
        For i As Integer = 0 To lines.GetUpperBound(0)
            values.Clear()
            values.AddRange(lines(i).Split(","))
            values.RemoveAt(100) ' Rmove 101st column
            lines(i) = String.Join(",", values.ToArray)
        Next

        For i As Integer = 0 To lines.GetUpperBound(0)
            values.Clear()
            values.AddRange(lines(i).Split(","))
            values.RemoveAt(77) ' Rmove 78th column
            lines(i) = String.Join(",", values.ToArray)
        Next

        For i As Integer = 0 To lines.GetUpperBound(0)
            values.Clear()
            values.AddRange(lines(i).Split(","))
            values.RemoveAt(85) ' Rmove 86th column
            lines(i) = String.Join(",", values.ToArray)
        Next

        System.IO.File.WriteAllLines(FileName, lines)
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok, I have figured out where my problem is.
Some of the fields have values like "Februare, 2010"
The script counts those commas as delimiters as well which is wrong.
Can we somehow 'skip' these particular cases. Otherwise, i was thinking about deleting these 3 columns via script in excel, I guess.
Are the commas for these values actually INSIDE quotes?
yes
you can look at test.csv
if you scroll to the right enough, you will see a value of FEBRUARY, 2011 in the cell(in excel)
in notepad it will look like this:
"something","something","something","February, 2011","sdfsdf"

I am looking at the csv file in notepad again and it looks like there is no easy way to split it in text mode vs excel mode.

1)some EMPTY columns are defined are "","", the otthers are just ,,

2)I thought about using "," for a delimiter value, but cells with dates do not have "" so it won't count right either

3) If we go excel route and delete column CV, and the other two, then I am wondering how I could provision it for Excel 2007 AND 2003.
Well...you can try going BACK to the TextFieldParser() approach and setting the HasFieldsEnclosedInQuotes() property to True:
http://msdn.microsoft.com/en-us/library/4y78s7xa(VS.80).aspx

    "Denotes whether fields are enclosed in quotation marks when parsing a delimited file."

Not sure it it will bomb since some of the fields do NOT have quotes!

Try it out and let us know how it goes:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim FileName As String = "c:\some\file.txt"
        Dim tfp As New Microsoft.VisualBasic.FileIO.TextFieldParser(FileName)
        tfp.TextFieldType = FileIO.FieldType.Delimited
        tfp.Delimiters = New String() {","}
        tfp.HasFieldsEnclosedInQuotes = True

        Dim lines As New List(Of String)
        Dim values As New List(Of String)
        While Not tfp.EndOfData
            values.Clear()
            values.AddRange(tfp.ReadFields)

            values.RemoveAt(99) ' Remove 100th column
            values.RemoveAt(87) ' Remove 88th column
            values.RemoveAt(84) ' Remove 85th column

            lines.Add(String.Join(",", values.ToArray))
        End While
        System.IO.File.WriteAllLines(FileName, lines.ToArray)
    End Sub

Open in new window

Ended up dealing with it via Excel in invisible mode. delimiters don't matter then. Everything works just as expected.

Thanks to all for help and ideas.
---------------------------------------------------------

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        Dim strFileName, objExcel, objWorkbook
        strFileName = "c:\test.csv"

        objExcel = CreateObject("Excel.Application")
        objExcel.DisplayAlerts = False
        objWorkbook = objExcel.Workbooks.Open(strFileName)
        objExcel.Visible = False

        objExcel.ActiveSheet.Columns("CW").Delete()
        objExcel.ActiveSheet.Columns("CJ").Delete()
        objExcel.ActiveSheet.Columns("CH").Delete()
        objExcel.ActiveWorkbook.Save()
        objExcel.Quit()
        MsgBox("File has been successfully processed!")


    End Sub