Excel导出文件,123.csv,用记事本打开看到是ANSI格式:
a1,b1,刘备,1
a2,b2,关羽,2
a3,b3,张飞,3
需要用VB6代码读取。
新建From1(窗体),新建Command1(按钮CommandButton),代码:
Private Sub Command1_Click()
Dim strFN As String
strFN = App.Path & "\123.csv"
Call s_readCSV(strFN)
End Sub
Private Sub s_readCSV(strFN As String)
Dim strLine As String, strAll As String
Dim i As Long
'检查文件是否在
If Dir(strFN) = "" Then
MsgBox "没有找到文件", vbCritical, "错误"
Exit Sub
End If
'将数据装入变量
Open strFN For Input As #1
Do Until EOF(1)
Line Input #1, strLine
strLine = Trim$(strLine)
If strLine <> "" Then
strAll = strAll & strLine & "|"
End If
DoEvents
Loop
Close #1
Dim strSP() As String
strSP = Split(strAll, "|")
For i = 0 To UBound(strSP)
Debug.Print strSP(i)
DoEvents
Next
End Sub
运行结果:
a1,b1,刘备,1
a2,b2,关羽,2
a3,b3,张飞,3
现在我们把123.csv通过记事本保存成UFT-8的格式,代码如下:
新建模块 modANSI2UTF.bas:
Public Function ReadUTF8(ByVal sUTF8File As String) As String
'If Len(sUTF8File) = 0 Or Dir(sUTF8File) = vbNullString Then Exit Function
Dim ados As Object
Set ados = CreateObject("adodb.stream")
With ados
.Charset = "utf-8"
.Type = 2
.Open
.LoadFromFile sUTF8File
ReadUTF8 = .ReadText
.Close
End With
Set ados = Nothing
End Function
Public Function UTF8_ANSI(ByVal sUTF8File As String, ByVal sANSIFile As String) As Boolean
'On Error GoTo errHandler
UTF8_ANSI = False
If Len(sUTF8File) = 0 Or Dir(sUTF8File) = vbNullString Then Exit Function
Dim ados As Object
Set ados = CreateObject("adodb.stream")
Dim fso As Object
Dim txtFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set txtFile = fso.CreateTextFile(sANSIFile, True)
With ados
.Charset = "utf-8"
.Type = 2
.Open
.LoadFromFile sUTF8File
txtFile.Write (.ReadText)
txtFile.Close
.Close
End With
Set ados = Nothing
UTF8_ANSI = True
errHandler:
If Err.Number <> 0 Then
MsgBox Err.Description, vbOKOnly + vbInformation, "UTF8_ANSI"
End If
End Function
然后新建From1(窗体),新建Command1(按钮CommandButton),代码:
Private Sub Command1_Click()
Dim strFN As String
strFN = App.Path & "\123.csv"
Call s_readCSV(strFN)
End Sub
Private Sub s_readCSV(strFN As String)
Dim strLine As String, strAll As String
'检查文件是否在
If Dir(strFN) = "" Then
MsgBox "没有找到文件", vbCritical, "错误"
Exit Sub
End If
strAll = ReadUTF8(strFN) '将数据装入变量
Dim strSP() As String
strSP = Split(strAll, "|")
Dim i As Long
For i = 0 To UBound(strSP)
Debug.Print strSP(i)
DoEvents
Next
End Sub
当然,这里模块采用的的是CreateObject("adodb.stream"),还有纯代码的就不公布了。