【问题标题】:VBA importing UTF-8 CSV file from a web serverVBA 从 Web 服务器导入 UTF-8 CSV 文件
【发布时间】:2014-06-30 20:29:40
【问题描述】:

我有一个 UTF-8 CSV 文件存储在网络服务器上。当我下载文件时,把它放在我的硬盘上,然后我用这个宏(来自宏记录器)将它导入到 Excel 表中:

Sub Macro2()
Workbooks.OpenText Filename:= _
    "C:/myFile.csv", Origin _
    :=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
    xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
    , Comma:=True, Space:=False, Other:=False
End Sub

所有字符(越南语字符)都正确显示。

当我尝试相同的宏但没有给出文件的本地地址(“C:/myFile.csv”)时,我传递了文件的 URL(“http://myserver.com/myFile.csv”),CSV 被正确导入到我的Excel 工作表,但越南语字符不再正确显示。

我也尝试过使用“数据”选项卡,但 Excel 似乎忽略了编码:

With ActiveSheet.QueryTables.Add(Connection:= _
                "TEXT;C:/myFile.csv" _
                , Destination:=Range("$A$1"))
                .Name = "myFile.csv"
                .FieldNames = True
                .RowNumbers = False
                .FillAdjacentFormulas = False
                .PreserveFormatting = True
                .RefreshOnFileOpen = False
                .RefreshStyle = xlInsertDeleteCells
                .SavePassword = False
                .SaveData = True
                .AdjustColumnWidth = True
                .RefreshPeriod = 0
                .TextFilePromptOnRefresh = False
                .TextFilePlatform = 65001
                .TextFileStartRow = 1
                .TextFileParseType = xlDelimited
                .TextFileTextQualifier = xlTextQualifierDoubleQuote
                .TextFileConsecutiveDelimiter = False
                .TextFileTabDelimiter = True
                .TextFileSemicolonDelimiter = False
                .TextFileCommaDelimiter = False
                .TextFileSpaceDelimiter = False
                .TextFileOtherDelimiter = "~"
                .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
                .TextFileTrailingMinusNumbers = True
                .Refresh BackgroundQuery:=False
       End With

样本数据:„; Â; ˜; Â1/4; ‰; ™,™

哪个 Excel 错误读取为:„; Â; ˜; Â1/4; ‰; ™,™;

【问题讨论】:

  • HTTP 标头中通常有编码声明。也许在你的情况下它被设置为另一个字符集并覆盖 Origin 参数
  • 谢谢,你知道我可以如何更改这些 HTTP 标头吗?
  • 取决于服务器。您可以使用 Web 浏览器轻松检查是否是这种情况:在 Firefox 中,您可以激活 Web 控制台,在地址栏中键入 URL 并查看响应标头 Content-type
  • 这里是内容类型:text/html; charset=UTF-8 所以这不应该是服务器问题吗?谢谢
  • 我的测试表明,当文件中没有 Unicode 字节顺序标记时,Excel 会感到困惑。如果有,它会从 URL 正确打开它,在这种情况下,服务器是否在标头中提供 charset=UTF-8 并不重要。

标签: excel vba csv utf-8


【解决方案1】:

IMO,使用记录的宏代码打开 UTF-8/UTF-8-BOM 文件时,Excel 中似乎存在错误/冲突,特别是当 Origin 参数设置为 65001应该是UTF-8。

我找到了两个解决这个问题的方法:

  1. 从函数调用中删除Origin参数,看看文件是否正确加载Workbooks.OpenText Filename:="C:\file.csv"

    MSDN says

    如果省略此参数,则该方法使用当前设置 文本导入向导中的文件来源选项。

    我认为,一旦您将文件与 Excel 链接,它应该尝试读取文件的标题并自动选择正确的Country Code好吧,假设标题没有丢失)。

  2. 我尝试了不同的Country Codes,发现在我的特定场景设置中Origin:=1252 (1252 - windows-1252 - ANSI Latin 1; Western European (Windows)) 可以很好地在 Excel 中加载文件。

    李>

【讨论】:

    【解决方案2】:

    如果您自己下载csv文件时字符显示正确,我会将过程分为2个阶段:

    正在下载

    Sub DownloadFile(ByVal url As String, ByVal local As String)
    
    Dim WinHttpReq As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", url, False, "username", "password"
    WinHttpReq.send
    
    myURL = WinHttpReq.responseBody
    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.responseBody
        oStream.SaveToFile local, 2 
        oStream.Close
    End If
    
    End Sub
    

    加载 CSV

    Sub OpenCsv(ByVal csvfile As String)
    Workbooks.OpenText Filename:= _ 
    csvfile,Local:=True,StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
    xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
    , Comma:=True, Space:=False, Other:=False
    End Sub
    

    注意:Local参数是这里的关键,它使VBA使用你的excel的本地配置(越南语),默认设置为False

    把它们放在一起

    Sub DownloadAndLoad
      DownloadFile "http://myserver.com/myFile.csv","C:\myFile.csv"
      OpenCsv "C:\myFile.csv"
    End Sub
    

    【讨论】:

    • 嗨,乌里。感谢您的回复。在我的情况下,Local:=True 并没有改变任何事情(是因为我的当地人是英国吗?改变我的语言环境并不是一个真正的选择,因为我将处理多种语言的文件......)。例如,csv文件中有一个™,当我使用Workbooks.Open时,字符仍然加载为„¢。我注意到,当我手动(而不是通过宏)执行此操作时,csv 已正确加载。我已经从手动步骤中记录了一个宏,但宏的行为是不同的。我已经读到 csv 文件可能缺少 UTF-8 标题 - 您是否熟悉标题?
    • Local 在读取 UTF-8 时不应使用或有影响。 @Meehow 是的,将UTF-8 BOM 放入文件fixes it
    【解决方案3】:

    我一直在研究一个类似的问题,我们将 utf-8 编码的 csv 文件导入到工作表中。我没有从 Web 服务器中提取数据,但这可能会有所帮助。

    我的解决方案是将 utf-8 文件读取到局部变量,然后将其插入工作表中。我尝试将数据保存到使用 ansi 编码的临时文件中,但这样做会导致所有字符丢失重音。

    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-13
      • 2012-11-18
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 2012-09-23
      相关资源
      最近更新 更多