VB6.0 读取CSV文件

最近做了一个Upload文件的需求,文件的格式为CSV,读取文件的方法整理了一下,如下:

1、先写了一个读取CSV文件的Function:

 '读取CSV文件
'假设传入的参数strFile=C:\Documents and Settings\Administrator\桌面\TPA_Report1 - 副本.CSV
Public Function Read_CSVFile(strFile As String) As ADODB.Recordset
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim strFilePath As String, strFileName As String
Dim i As Integer
i = Len(strFile)
Do Until Mid(strFile, i, ) = "\" '从后向前查找倒数第一个"\"
i = i -
Loop
strFilePath = Left(strFile, i - ) '返回结果:C:\Documents and Settings\Administrator\桌面
strFileName = Mid(strFile, InStrRev(strFile, "\") + 1) '返回结果:TPA_Report1 - 副本.CSV conn.Open "DRIVER={Microsoft Text Driver (*.txt; *.csv)};" & _
"DBQ=" & strFilePath & ";", "", "" rs.Open "select * from [" & strFileName & "]", conn, adOpenStatic, _
adLockReadOnly, adCmdText
Set Read_CSVFile = rs
Set rs = Nothing
Set conn = Nothing
End Function

2、调用上面的Function:

 Private Sub cmdUpload_Click()
Dim rsData As ADODB.Recordset 'CSV中的所有的数据
Dim rsUploadLog As ADODB.Recordset '上传纪录 '取得CSV中所有的数据
Set rsData = Read_CSVFile(txtFileName.Text) If rsData.RecordCount > Then
DoEvents
Dim iTotal As Integer
iTotal = rsData.MoveFirst
Do While Not rsData.EOF '循环数据集
'UploadLog
rsUploadLog.AddNew
rsUploadLog!Row = iTotal +
rsUploadLog!Createby = sUserID
rsUploadLog!CreateDate = dServerdateTime
rsUploadLog!Note = rsData.Fields("投保人名字") & "" '“投保人名字”为CSV文件的表头
iTotal = iTotal +
DoEvents
rsData.MoveNext
Loop '一批数据里面有的成功,有的失败.进行保存的时候,成功的就保存更新,不成功的就不保存
If Not BatchSaving(conn, rsUploadLog) = True Then
MsgBox "Upload un-successfully done", vbInformation, sApplicName
Else
MsgBox "Upload successfully done", vbInformation, sApplicName
End If
End If
'释放资源,否则CSV打开会是只读状态
rsData.Close
Set rsData.ActiveConnection = Nothing
Set rsData = Nothing
Exit Sub
End Sub
上一篇:[nRF51822] 7、基础实验代码解析大全(前十)


下一篇:php读取csv文件,在linux上出现中文读取不到的情况 解决方法