VBAmacros将excel分析保存为UTF-8文本文件

我有一个包含一些外来字符的XLS文件。 我已经尝试了以下方法,但数据看起来很时髦:

--- removed code above wb.SaveAs fPath & Replace(fName, ".xlsx", ".txt"), FileFormat:=xlUnicodeText, CreateBackup:=False wb.Saved = True wb.Close True ActiveWorkbook.Close tFileToOpenPath = fPath & Replace(fName, ".xlsx", ".txt") tFileToSavePath = fPath & Replace(fName, ".xlsx", "-UTF8.txt") Dim oStream Set oStream = CreateObject("ADODB.Stream") 'Create Stream object With oStream .Type = 2 'Specify stream type – we want To save text/string data. .CharSet = "utf-8" 'Specify charset For the source text data. .Open 'Open the stream .LoadFromFile tFileToOpenPath 'And write the file to the object stream .SaveToFile tFileToSavePath, 2 'Save the data to the named path End With Set oStream = Nothing 'Close the stream - no memory leaks 

输出的数据看起来像…我很困惑

 S ales 

txt文件本身很好,只是UTF-8.txt真的很奇怪

谢谢!

以下是发生的事情:
wb.SaveAs将您的工作簿保存为xlUnicodeText 。 这实际上是UTF16LE(当人们只是说'Unicode'时,主要是这个意思)。

您的stream对象打开此UTF16源,但读取它为UTF8。 在UTF16中,字符占用至less两个字节。 在UTF8中,简单的拉丁字符只使用一个字节,因此在大多数字符之后是一个空字节(以空格显示; notepad ++会显示NUL )。

这似乎适用于转换:

 Public Sub convert_UnicodeToUTF8(parF1 As String, parF2 As String) Const adSaveCreateOverWrite = 2 Const adTypeText = 2 Dim streamSrc, streamDst ' Source / Destination Set streamSrc = CreateObject("ADODB.Stream") Set streamDst = CreateObject("ADODB.Stream") streamDst.Type = adTypeText streamDst.Charset = "utf-8" streamDst.Open With streamSrc .Type = adTypeText .Charset = "Unicode" ' this is also the default value .Open .LoadFromFile parF1 .copyTo streamDst .Close End With streamDst.saveToFile parF2, adSaveCreateOverWrite streamDst.Close Set streamSrc = Nothing Set streamDst = Nothing End Sub 

请参阅ADODB.Stream.CopyTo 。

目标Stream对象的CharSet属性可以不同于源Stream对象