近日发现有一办法,可以较好的解决这个问题。即是采用ADO的方式,将字符串生成以指定字符集的流文件输出。
函数代码如下,VB或VBA中均可用。注意:需要添加对ADO 对象库的引用。
ADO方式写入
'功能:text保存为文件(ADO方式)
'输入:输出文件地址、内容文本、字符集
'输出:无
Sub WriteToTextFileADO(filePath As String, strContent As String, CharSet As String)
Set stm = New ADODB.Stream
stm.Type = 2 '以本模式读取
stm.Mode = 3
stm.CharSet = CharSet
stm.Open
stm.WriteText strContent
'如果文件存在,删除文件
If Len(Dir(filePath)) > 0 Then
Kill filePath
End If
stm.SaveToFile filePath, 2
stm.Flush
stm.Close
Set stm = Nothing
End Sub
'输入:输出文件地址、内容文本、字符集
'输出:无
Sub WriteToTextFileADO(filePath As String, strContent As String, CharSet As String)
Set stm = New ADODB.Stream
stm.Type = 2 '以本模式读取
stm.Mode = 3
stm.CharSet = CharSet
stm.Open
stm.WriteText strContent
'如果文件存在,删除文件
If Len(Dir(filePath)) > 0 Then
Kill filePath
End If
stm.SaveToFile filePath, 2
stm.Flush
stm.Close
Set stm = Nothing
End Sub
使用示例:
Call WriteToTextFileADO(Sheets("channel-list").Cells(3, 5) & "\" & feedName & ".xml", feedXml, "utf-8")
ADO方式读取
'功能:读取text文件(ADO方式)
'输入:输入文件地址、字符集
'输出:无
Function ReadFromFileADO(filePath As String, CharSet As String) As String
Dim strRtn As String
Set stm = New ADODB.Stream
stm.Type = 2 '以本模式读取
stm.Mode = 3
stm.CharSet = CharSet
stm.Open
stm.LoadFromFile filePath
strRtn = stm.ReadText
stm.Close
Set stm = Nothing
ReadFromFileADO = strRtn
End Function
'输入:输入文件地址、字符集
'输出:无
Function ReadFromFileADO(filePath As String, CharSet As String) As String
Dim strRtn As String
Set stm = New ADODB.Stream
stm.Type = 2 '以本模式读取
stm.Mode = 3
stm.CharSet = CharSet
stm.Open
stm.LoadFromFile filePath
strRtn = stm.ReadText
stm.Close
Set stm = Nothing
ReadFromFileADO = strRtn
End Function