最近做了一个Upload文件的需求,文件的格式为CSV,读取文件的方法整理了一下,如下:
1、先写了一个读取CSV文件的Function:
1 '读取CSV文件 2 '假设传入的参数strFile=C:\Documents and Settings\Administrator\桌面\TPA_Report1 - 副本.CSV 3 Public Function Read_CSVFile(strFile As String) As ADODB.Recordset 4 Dim rs As ADODB.Recordset 5 Set rs = New ADODB.Recordset 6 Dim conn As ADODB.Connection 7 Set conn = New ADODB.Connection 8 Dim strFilePath As String, strFileName As String 9 Dim i As Integer 10 i = Len(strFile) 11 Do Until Mid(strFile, i, 1) = "\" '从后向前查找倒数第一个"\" 12 i = i - 1 13 Loop 14 strFilePath = Left(strFile, i - 1) '返回结果:C:\Documents and Settings\Administrator\桌面 15 strFileName = Mid(strFile, InStrRev(strFile, "\") + 1) '返回结果:TPA_Report1 - 副本.CSV 16 17 conn.Open "DRIVER={Microsoft Text Driver (*.txt; *.csv)};" & _ 18 "DBQ=" & strFilePath & ";", "", "" 19 20 rs.Open "select * from [" & strFileName & "]", conn, adOpenStatic, _ 21 adLockReadOnly, adCmdText 22 Set Read_CSVFile = rs 23 Set rs = Nothing 24 Set conn = Nothing 25 End Function
2、调用上面的Function:
1 Private Sub cmdUpload_Click() 2 Dim rsData As ADODB.Recordset 'CSV中的所有的数据 3 Dim rsUploadLog As ADODB.Recordset '上传纪录 4 5 '取得CSV中所有的数据 6 Set rsData = Read_CSVFile(txtFileName.Text) 7 8 If rsData.RecordCount > 0 Then 9 DoEvents 10 Dim iTotal As Integer 11 iTotal = 0 12 13 rsData.MoveFirst 14 Do While Not rsData.EOF '循环数据集 15 'UploadLog 16 rsUploadLog.AddNew 17 rsUploadLog!Row = iTotal + 1 18 rsUploadLog!Createby = sUserID 19 rsUploadLog!CreateDate = dServerdateTime 20 rsUploadLog!Note = rsData.Fields("投保人名字") & "" '“投保人名字”为CSV文件的表头 21 iTotal = iTotal + 1 22 DoEvents 23 rsData.MoveNext 24 Loop 25 26 '一批数据里面有的成功,有的失败.进行保存的时候,成功的就保存更新,不成功的就不保存 27 If Not BatchSaving(conn, rsUploadLog) = True Then 28 MsgBox "Upload un-successfully done", vbInformation, sApplicName 29 Else 30 MsgBox "Upload successfully done", vbInformation, sApplicName 31 End If 32 End If 33 '释放资源,否则CSV打开会是只读状态 34 rsData.Close 35 Set rsData.ActiveConnection = Nothing 36 Set rsData = Nothing 37 Exit Sub 38 End Sub
如果您看了本篇博客,觉得对您有所收获,请点击右下角的 [推荐]
如果您想转载本博客,请注明出处
如果您对本文有意见或者建议,欢迎留言
感谢您的阅读,请关注我的后续博客