VBA importing UTF-8 CSV file from a web server

后端 未结 3 1161
花落未央
花落未央 2021-02-18 18:39

I have a UTF-8 CSV file stored on a web server. When I download the file put it on my hard drive and I then import it into an Excel sheet with this macro (from the macro recorde

3条回答
  •  别那么骄傲
    2021-02-18 19:13

    I have been looking at a similar problem where we import utf-8 encoded csv files in to a worksheet. I am not pulling the data from a web server but this might help.

    My solution is to read the utf-8 file to a local variable then insert it into a sheet. I tried saving the data to a temp file with ansi encoding but doing this caused all the characters to lose their accents.

    Function ReadUTF8CSVToSheet(file As String)
        Dim ws As Worksheet
        Dim strText As String
    
        ' read utf-8 file to strText variable
       With CreateObject("ADODB.Stream")
            .Open
            .Type = 1  ' Private Const adTypeBinary = 1
            .LoadFromFile file
            .Type = 2  ' Private Const adTypeText = 2
            .Charset = "utf-8"
            strText = .ReadText(-1)  ' Private Const adReadAll = -1
        End With
    
        ' parse strText data to a sheet
        Set ws = Sheets.Add()
        intRow = 1
        For Each strLine In Split(strText, chr(10))
            If strLine <> "" Then
                With ws
                    .Cells(intRow, 1) = strLine
                    .Cells(intRow, 1).TextToColumns Destination:=Cells(intRow, 1), DataType:=xlDelimited, _
                        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
                        Semicolon:=False, Comma:=True, Space:=False, Other:=False
                End With
    
                intRow = intRow + 1
            End If
        Next strLine
    
        ReadUTF8CSVToSheet = ws.Name
    
    End Function
    
    ' to run
    strSheetName = ReadUTF8CSVToSheet("C:\temp\utf8file.csv")
    

提交回复
热议问题