如何使用Excel for Mac 2011将工作表保存为UTF-8格式的CSV文件?

我有以下Excel VBA脚本,我用于Mac 2011的Excel中将Excel文件的所有工作表导出到.csv文件。

Sub save_all_csv() On Error Resume Next Dim ExcelFileName As String ExcelFileName = ThisWorkbook.Name For Each objWorksheet In ThisWorkbook.Worksheets ExcelFileNameWithoutExtension = RemoveExtension(ExcelFileName) CsvFileName = ExcelFileNameWithoutExtension & "__" & objWorksheet.Name & ".csv" Application.DisplayAlerts = False objWorksheet.SaveAs Filename:="data:storage:original_excel:" & CsvFileName, FileFormat:=xlCSV, CreateBackup:=False Application.DisplayAlerts = True Next Application.DisplayAlerts = False Application.Quit End Sub Function RemoveExtension(strFileName As String) strFileName = Replace(strFileName, ".xlsx", "") strFileName = Replace(strFileName, ".xls", "") RemoveExtension = strFileName End Function 

问题是,他们保存为西方的Mac OS罗马 ,我无法通过PHP转换为UTF-8,所以我想有VBA保存这些文件在UTF-8格式的第一位。

替代文字

我发现了一些解决scheme,通过Stream对象和CreateObject保存VBA文本,但是显然在Mac上不能使用CreateObject直接写入文件 。

如何使用Excel for Mac 2011将工作表保存为UTF-8格式的CSV文件?

我认为你是对的,你将不得不自己做文件创build,我相当确定你不能使用CreateObject来创buildstream。 然而,你可能想要使用Open,Write等(大量的例子,但这里有一个 )。 我会先做一个非常小的实验,只是为了检查最终的编码。

克里斯

我有同样的问题,最终只写了一个例程编码为utf-8 。 此代码适用于Mac上的MacBook Pro:Excel 2011.只需使用由此函数创build的字节数组来执行二进制文件输出即可 。 在我的情况下,我正在处理泰语脚本,以便自动使用Mac的优秀的语音合成器。

 Private Function UTF8Encode(b() As Byte) As Byte() ' Function to convert a Unicode Byte array into a byte array that can be written to create a UTF8 Encoded file. ' Note the function supports the one, two and three byte UTF8 forms. ' Note: the MS VBA documentation is confusing. It says the String types only supports single byte charset ' however, thankfully, it does in fact contain 2 byte Unicode values. ' Wrote this routine as last resort, tried many ways to get unicode chars to a file or to a shell script call ' but this was the only way could get to work. ' RT Perkin ' 30/10/2015 Dim b1, b2, b3 As Byte ' UTF8 encoded bytes Dim u1, u2 As Byte ' Unicode input bytes Dim out As New Collection ' Collection to build output array Dim i, j As Integer Dim unicode As Long If UBound(b) <= 0 Then Exit Function End If For i = 0 To UBound(b) Step 2 u1 = b(i) u2 = b(i + 1) unicode = u2 * 256 + u1 If unicode < &H80 Then ' Boils down to ASCII, one byte UTF-8 out.Add (u1) ElseIf unicode < &H800 Then ' Two byte UTF-8 ' Code path not tested b1 = &H80 Or (&H3F And u1) b2 = &HC0 Or (Int(u1 / 64)) Or ((&H7 And u2) * 4) out.Add (b2) ' Add most significant byte first out.Add (b1) ElseIf unicode < &H10000 Then ' Three byte UTF-8 ' Thai chars are in this range b1 = &H80 Or (&H3F And u1) b2 = &H80 Or (Int(u1 / 64)) Or ((&HF And u2) * 4) b3 = &HE0 Or (Int(u2 / 16)) out.Add (b3) ' Add most significant byte first out.Add (b2) out.Add (b1) Else ' This case wont arise as VBA strings are 2 byte. Which makes some Unicode codepoints uncodeable. End If Next Dim outBytes() As Byte ReDim outBytes(1 To out.Count) For j = 1 To out.Count outBytes(j) = CByte(out.Item(j)) Next UTF8Encode = outBytes End Function