如题。。。
是将文件转换,不是字符串哦。。。
求VB将UTF-8编码的TXT文件转换成ANSI编码的代码
答案:4 悬赏:0 手机版
解决时间 2021-02-04 15:48
- 提问者网友:凉末
- 2021-02-03 17:32
最佳答案
- 五星知识达人网友:拜訪者
- 2021-02-03 18:16
如楼上所说,楼主提问前也不百度一下
全部回答
- 1楼网友:你哪知我潦倒为你
- 2021-02-03 18:59
charset设置为utf-8即可
function bytestobstr(body, charset)
dim objstream
set objstream = createobject("adodb.stream")
objstream.type = 1
objstream.mode = 3
objstream.open
on error resume next
objstream.write body
objstream.position = 0
objstream.type = 2
objstream.charset = charset
bytestobstr = objstream.readtext
objstream.close
set objstream = nothing
end function
- 2楼网友:三千妖杀
- 2021-02-03 18:51
立一个模块,复制下面代码
Option Explicit
Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByRef lpMultiByteStr As Any, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
Private Const CP_UTF8 = 65001
'读文件至变量
Private Function GetFile(FileName As String) As String
Dim i As Integer, BB() As Byte
If Dir(FileName) = "" Then Exit Function
i = FreeFile
ReDim BB(FileLen(FileName) - 1)
Open FileName For Binary As #i
Get #i, , BB
Close #i
GetFile = BB
End Function
'功能: 把Utf8字符转化成ANSI字符
Public Function UTF8_Decode(FileName As String) As String
Dim sUTF8 As String
Dim lngUtf8Size As Long
Dim strBuffer As String
Dim lngBufferSize As Long
Dim lngResult As Long
Dim bytUtf8() As Byte
Dim n As Long
sUTF8 = GetFile(FileName)
If LenB(sUTF8) = 0 Then Exit Function
On Error GoTo EndFunction
bytUtf8 = sUTF8
lngUtf8Size = UBound(bytUtf8) + 1
lngBufferSize = lngUtf8Size * 2
strBuffer = String$(lngBufferSize, vbNullChar)
lngResult = MultiByteToWideChar(CP_UTF8, 0, bytUtf8(0), _
lngUtf8Size, StrPtr(strBuffer), lngBufferSize)
If lngResult Then
UTF8_Decode = Left(strBuffer, lngResult)
End If
EndFunction:
End Function
二、调用举例:
如果你想把一个"c:\1.txt"的UTF-8文件转换为ANSI编码,可这样调用
dim s as string
s=UTF8_Decode("c:\1.txt") '文件名请根据实际修改
此时,s存放的就是ANSI格式编码了,不会出现乱码问题
- 3楼网友:洎扰庸人
- 2021-02-03 18:46
用编码转换工具就可以了。下载一个飞梭TXT文本数据处理百宝箱,就可以直接转换。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯