VBA 웹 서버에서 UTF-8 CSV 파일 가져오기
웹 서버에 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; ‰; ™,™;
다운로드 시 문자가 올바르게 표시되는 경우csv
직접 파일을 작성하면 프로세스를 두 단계로 나눕니다.
다운로드 중
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
저는 utf-8 인코딩된 csv 파일을 워크시트로 가져오는 유사한 문제를 보고 있습니다.웹 서버에서 데이터를 가져오지는 않지만 도움이 될 수 있습니다.
나의 해결책은 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")
IMO, 특히 기록된 매크로 코드를 사용하여 UTF-8/UTF-8-BOM 파일을 열 때 Excel에 버그/충돌이 있는 것 같습니다.Origin
매개 변수가 다음으로 설정됨65001
UTF-8로 추정됩니다.
이 문제에 대한 두 가지 해결 방법을 찾았습니다.
제거합니다.
Origin
함수 호출의 매개 변수 및 파일이 제대로 로드되는지 확인합니다.Workbooks.OpenText Filename:="C:\file.csv"
.MSDN은 다음과 같이 말합니다.
이 인수를 생략하면 메서드는 텍스트 가져오기 마법사의 파일 원본 옵션의 현재 설정을 사용합니다.
엑셀로 파일을 링크하는 즉시 파일의 헤더를 읽고 올바른 국가 코드를 자동으로 선택해야 한다고 생각합니다(글쎄요, 헤더가 누락되지 않았다고 가정하면).
다른 국가 코드를 시도해 본 결과 특정 시나리오 설정에서 다음 사항을 확인했습니다.
Origin:=1252
() 파일을 Excel에 로드하면 됩니다.1252 - windows-1252 - ANSI Latin 1; Western European (Windows)
언급URL : https://stackoverflow.com/questions/23626622/vba-importing-utf-8-csv-file-from-a-web-server
'programing' 카테고리의 다른 글
도짓 태그도 밀립니까? (0) | 2023.07.11 |
---|---|
해당 값으로 연결된 키 선택 (0) | 2023.07.11 |
Firebase Firestore의 수집 스냅샷 항목 매핑 (0) | 2023.07.11 |
잘못된 정방향 참조 또는 컴파일되지 않은 형식에 대한 참조 (0) | 2023.07.11 |
부하가 있는 동안 기본값으로 열을 추가하는 가장 좋은 방법 (0) | 2023.07.11 |