импорт CSV-файла с разделителями-запятыми с запятыми в длинных числах - PullRequest
1 голос
/ 24 февраля 2012

Я пытаюсь импортировать CSV-файл с разделителями-запятыми в доступе.Проблема, с которой я столкнулся, заключается в том, что в одном из столбцов «Сумма» есть запятые в самих данных, например «1433,36».И в этих данных всегда будут запятые.

Как успешно импортировать?

Пример данных:

sjonn,one,"1,855.9"
ptele,two,344.0
jrudd,one,334.8

Заранее спасибо

Ответы [ 5 ]

1 голос
/ 29 февраля 2012

Если DoCmd.TransferText не работает для вас, вы можете определить метод, который будет делать это «вручную»:

Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = fs.GetFile("import.txt")
Set objFileTextStream = objFile.OpenAsTextStream(1, 2)

objFileTextStream.skipLine 'if the file contains the header

Do While objFileTextStream.AtEndOfStream <> True 
    strLine = objFileTextStream.ReadLine 'read a line
    strLinePart = split(strLine,",")  'Split the line using the , delimiter
    firstField = strLinePart(0)
    secondField = strLinePart(1)
    thirdField = strLinePart(2)
    strSQL = "INSERT INTO myTable Values('"& firstField &"','"& secondField &"','"& thirdField &"')"
  conn.Execute strSQL
Loop

objFileTextStream.Close: Set objFileTextStream = Nothing
Set fs = Nothing
conn.Close: Set conn = Nothing 
1 голос
/ 24 февраля 2012

Я бы изменил разделитель на другой символ, например, на «|».

0 голосов
/ 16 августа 2013

Однажды я столкнулся с проблемой, и это еще один метод, который может помочь, однако он разбивает сами строки, т. Е. Перед использованием этого метода необходимо сначала разбить строку на строки Также предполагается, что он содержится в модуле с именем Module1

    ''Perfoms a smart split that takes care of the ""
    Public Function SmartSplit(Str As String) As Variant

    ''New collection
    Dim Quote As String
    Dim Delimiter As String
    Dim MyString As String
    Dim Sample As String
    Dim StrCollection As New Collection
    Dim Array_1() As String
    Dim HasSeenQuote As Boolean
    Dim index As Long

    Quote = "" & CStr(Chr(34))
    Delimiter = "" & CStr(Chr(44))
    HasSeenQuote = False



    Array_1 = Split(Str, Delimiter)


    For index = LBound(Array_1) To UBound(Array_1)

    Sample = Array_1(index)

    If Module1.StartsWith(Sample, Quote, False) Then
    HasSeenQuote = True
    End If

    ''We append the string
    If HasSeenQuote Then
    MyString = MyString & "," & Sample
    End If


    ''We add the term
    If Module1.EndsWith(Sample, Quote, False) Then
    HasSeenQuote = False

        MyString = Replace(MyString, Quote, "")
        MyString = Module1.TrimStartEndCharacters(MyString, ",", True)
        MyString = Module1.TrimStartEndCharacters(MyString, Quote, True)
        StrCollection.Add (MyString)
        MyString = ""
        GoTo LoopNext

    End If

    ''We did not see a quote before
    If HasSeenQuote = False Then
            Sample = Module1.TrimStartEndCharacters(Sample, ",", True)
            Sample = Module1.TrimStartEndCharacters(Sample, Quote, True)
            StrCollection.Add (Sample)
    End If


    LoopNext:
    Next index



    ''Copy the contents of the collection
    Dim MyCount As Integer
    MyCount = StrCollection.Count

    Dim RetArr() As String
    ReDim RetArr(0 To MyCount - 1) As String

    Dim X As Integer
    For X = 0 To StrCollection.Count - 1 ''VB Collections start with 1 always
        RetArr(X) = StrCollection(X + 1)
    Next X

    SmartSplit = RetArr

    End Function


    ''Returns true of false if the string starts with a string
    Public Function EndsWith(ByVal Str As String, Search As String, IgnoreCase         As         Boolean) As Boolean

    EndsWith = False
    Dim X As Integer
    X = Len(Search)

    If IgnoreCase Then
    Str = UCase(Str)
    Search = UCase(Search)
    End If


    If Len(Search) <= Len(Str) Then

    EndsWith = StrComp(Right(Str, X), Search, vbBinaryCompare) = 0

    End If


    End Function



    ''Trims start and end characters
    Public Function TrimStartEndCharacters(ByVal Str As String, ByVal Search As         String, ByVal IgnoreCase As Boolean) As String

    If Module1.StartsWith(Str, Search, IgnoreCase) Then
     Str = Right(Str, (Len(Str) - Len(Search)))
    End If

    If Module1.EndsWith(Str, Search, IgnoreCase) Then
        Str = Left(Str, (Len(Str) - Len(Search)))
    End If

    TrimStartEndCharacters = Str

    End Function


    ''Returns true of false if the string starts with a string
    Public Function StartsWith(ByVal Str As String, Search As String, IgnoreCase As Boolean) As Boolean

    StartsWith = False
    Dim X As Integer
    X = Len(Search)

    If IgnoreCase Then
    Str = UCase(Str)
    Search = UCase(Search)
    End If


    If Len(Search) <= Len(Str) Then

    StartsWith = StrComp(Left(Str, X), Search, vbBinaryCompare) = 0

    End If


    End Function
0 голосов
/ 25 февраля 2012

чтение файла с помощью ввода обрабатывает кавычки для вас

Dim f1 As String
Dim f2 As String
Dim f3 As String

Open "d:\test.txt" For Input As #1

Input #1, f1, f2, f3
Debug.Print f1, f2, f3
Input #1, f1, f2, f3
Debug.Print f1, f2, f3

Close #1 '

давая

sjonn         one           1,855.9
ptele         two           344.0
0 голосов
/ 24 февраля 2012

Сохраните файл как текстовый файл с разделителями табуляции и импортируйте его.

...