VBA 使用MADC的ADODB.Stream生成UTF-8文本文件(去掉BOM頭)

2017-07-26 17:44:00
zstmtony
轉貼
1322


VBA 使用MADC的ADODB.Stream生成UTF-8文本文件(去掉BOM頭)


作者:masterjian


主要實現思路是使用 ADODB.Stream

主要關鍵代碼如下:


Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText "special characters: äöüß"
fsT.SaveToFile sFileName, 2 'Save binary data To disk


前段時間,因爲項目需要,需要用Excel管理國際化資源文件的字符串,
旨在用VBA直接生成資源文件。

但是遇到一箇問題,就是:

VBA生成的文本文件,默認是Gb2312編碼(與繫統的一緻),所以我就
隻能生成UTF-8格式的瞭。但是,用FSO生成的UTF格式是【UTF-16LE】
VS2008不識彆。。。
鬱悶之餘,隻能用MADC來生成。但是,情況又齣現瞭,用MADC生成的UTF-8
文件默認是帶BOM頭的。。。

所以,逼上樑山的我就這能用下麵的辦法來實現UTF-8 無BOM頭的寫:

Private Sub WriteOut(strPath As String, str As String)

    Dim objStream As Object
    Set objStream = CreateObject("ADODB.Stream")
    
    With objStream
        .Type = 2               'adTypeText
        .Charset = "UTF-8"
        .Open
        .WriteText str
        .SaveToFile strPath, 2  'adSaveCreateOverWrite
    End With
    
    Set objStream = Nothing
End Sub


Public Function Convert2utf8(fileName As String, FileTo As String) As Boolean


    Dim ReadIntFileNum, WriteIntFileNum As Integer
    ReadIntFileNum = FreeFile() '穫取一箇空文件
    WriteIntFileNum = FreeFile() + 1
    
    
    Open fileName For Binary As ReadIntFileNum
    Open FileTo For Binary As #WriteIntFileNum
'    Dim byteFrom, byteTo As String
    Dim fileByte As Long
    Seek #ReadIntFileNum, 4
   
    While Not EOF(ReadIntFileNum)
    
        Get #ReadIntFileNum, , fileByte
        Put #WriteIntFileNum, , fileByte
    Wend
    
    Close #ReadIntFileNum
    Close #WriteIntFileNum
    Kill fileName
End Function


在使用的時候,先用WriteOut生成一箇臨時文件(UTF-8帶BOM),
然後用Convert2utf8將BOM頭的前三箇字節刪除。
分享