2010-04-29 8 views
1

CVS 파일을 읽는 데이 코드가 있습니다. 각 행을 읽고, 각 행을 구분 기호 ','로 나누고 필드 값을 배열 'strline()'에 저장합니다.vb.net의 CSV 파일에서 특정 필드 만 읽기

CSV 파일에서 필수 입력란 만 어떻게 추출합니까? 나는 CSV가

유형, 그룹과 같은 파일이있는 경우

예를 들어, 아니, 순서 아니, 날짜 (줄 바꿈) 0, 관리자, 3,345678,1,26052010 (줄 바꿈) 1 @ 행 , Staff, 5,78654,3,26052010

난 그룹의 값, 시퀀스 번호 및 날짜 만 필요합니다.

미리 아이디어를 제공해 주셔서 감사합니다.

Dim myStream As StreamReader = Nothing 
    ' Hold the Parsed Data 
    Dim strlines() As String 
    Dim strline() As String 
    Try 
     myStream = File.OpenText(OpenFile.FileName) 
     If (myStream IsNot Nothing) Then 
     ' Hold the amount of lines already read in a 'counter-variable' 
     Dim placeholder As Integer = 0 
     strlines = myStream.ReadToEnd().Split(Environment.NewLine) 
     Do While strlines.Length <> -1 ' Is -1 when no data exists on the next line of the CSV file 
      strline = strlines(placeholder).Split(",") 
      placeholder += 1 
     Loop 
     End If 
    Catch ex As Exception 
     LogErrorException(ex) 

    Finally 

     If (myStream IsNot Nothing) Then 
     myStream.Close() 
     End If 
    End Try 

답변

7

1) String.Split를 사용하지 마십시오!

CSV 데이터에는 쉼표가 포함될 수 있습니다 (예 :

id,name 
1,foo 
2,"hans, bar" 

또한 당신은 자세한 내용은 CSV Info보기 ... 등등 인용 필드를 처리 할 필요가 위와 같이.

2) TextFieldParser을 확인하십시오. MyReader.ReadFields() 부분은 당신에게 문자열 배열을 얻을 것이다 http://msdn.microsoft.com/en-us/library/cakac7e6.aspx

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.txt") 
    MyReader.TextFieldType = FileIO.FieldType.Delimited 
    MyReader.SetDelimiters(",") 
    Dim currentRow As String() 
    While Not MyReader.EndOfData 
     Try 
      currentRow = MyReader.ReadFields() 
      Dim currentField As String 
      For Each currentField In currentRow 
      MsgBox(currentField) 
      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 

:에서

그것은 당신 사항 String.split와 함께 할 수없는 다른 탈출의 무수를 처리 할 ...

샘플 거기에서 당신이

+1

+1 string.split은 잘못된 것일뿐만 아니라 상태 기계에 비해 속도가 매우 느립니다. –

+1

+1은 OP에서 중요한 경고를 외쳤습니다. –

+0

String.Split 및 "일반적으로 기타"에 대한 경고가 좋겠지 만 데이터는 어디에서 왔으며 사양은 무엇인지에 따라 다릅니다. 대부분의 경우 CSV 파일을 읽고 문자열을 사용했습니다. 분할, 내가 너무 많은 열로 끝나면 파일을 잃어 버렸고 파일의 제작자에게 데이터를 수정하라고 말했습니다. –

0

어쩌면 대신 선택된를 임포트 필드 :-) ... 인덱스 등을 사용하는

PK가 필요합니다, 모든 것을 가져 와서 필요한 것만 사용해야합니다.