将分隔文件(.csv)中的行导入MS-Access表

时间:2014-06-19 14:29:43

标签: vba csv access-vba ado

系统背景:我在Access 2010中使用用户界面和存储数据库的Microsoft SQL Server 2008后端。

问题背景:我实验室中的计算机以.csv文件的形式输出结果。这些文件放在服务器上的文件夹中。目前,结果手动输入数据库。目标是让一个访问程序(VBA)逐行读入文件中的数据,并将文件的每一行插入数据库中的特定表。我被告知我们ADO对象来实现这一目标。

进度:我的问题在于尝试读取分隔文件的每一行。我得到了一个参考网站http://msdn.microsoft.com/en-us/library/ms974559.aspx,但当我尝试在副标题下如何使用ADO查询文本文件时实现该示例?并且我得到了一些错误,坚持使用方法在连接时没有特别发现。打开。我想获取每一行的值并将它们存储到临时变量中以传递给存储过程。已创建存储过程,并且已创建插入新记录的过程。

代码旁注:代码是较低级别的函数,这意味着它一次不会读取文件夹中的所有.csv文件。该函数由更高级别的函数给出一个文件名,该函数将从该文件名中读取指定文件的每一行,并将其存储在表格中,并将其存储在表格中。#34; tblICPMS"。以下是在excel enter image description here

中打开时.cvs文件的样子

这是我的代码:

Public Function ImportICPMS(ThisFileName As String, ThisQueueID As Long, BatchID
As Long, InstrumentName As String, TechId As Long)
On Error GoTo HandleError

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Dim obj_fso As Object
Dim objconnection As connection
Dim objRecordset As Recordset
Dim strpathtotextfile As String

'test if file exists (newpath is a public path to folder)'
Set obj_fso = CreateObject("Scripting.FileSystemObject")
If obj_fso.FileExists(NewPath & "\" & ThisFileName) Then
Else
    Err.Raise vbObjectError + 1000, "MyProjectName.MyObjectName", "file " & ThisFileName & " for " & InstrumentName & " not found" 'if false error is raised
End If

Set objconnection = CreateObject("ADODB.connection") 'create ADO objects'
Set objRecordset = CreateObject("ADODB.recordset")

strpathtotextfile = NewPath & "\" 'path to folder where file resides'

objconnection.Open "Provider=SQLOLEDB.1;Data Source=strpathtotextfile;Extended Properties=;HDR = YES;FMT = Delimited"

objrecordset.Open "SELECT * FROM " & ThisFileName,objconnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF

'I do not know what Wscript.Echo means but I want to save the acquired values into
 temp variables to pass them to a stored procedure that inserts them into the table'

Wscript.Echo objRecordset.Fields.Item("Sample Name")
Wscript.Echo objRecordset.Fields.Item("Date and Time Acquired")
Wscript.Echo objRecordset.Fields.Item("Element Full Name")
Wscript.Echo objRecordset.Fields.Item("Concentration")
Wscript.Echo objRecordset.Fields.Item("Units")

'code to insert rows into table would probably go here'
'code to clear out local objects would go here'

objRecordset.MoveNext

Loop
objRecordset.Close
objconnection.Close

我没有包含其余代码或存储过程,但如果有人想看到它们,我可以。我想把我插入的代码集中在我正在处理的部分上。

2 个答案:

答案 0 :(得分:1)

您使用该提供程序的方法可能是因为它没有正确打开CSV。 据我所知,SQLOLEDB.1没有此文本阅读器功能。

试试这个,改变:

objconnection.Open "Provider=SQLOLEDB.1;Data Source=strpathtotextfile;Extended Properties=;HDR = YES;FMT = Delimited"

对此,

objconnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=strpathtotextfile;Extended Properties=""Text;HDR=YES;FMT=Delimited"""

更新:注意到声明存在问题:

Dim objconnection As connection
Dim objRecordset As Recordset

应该工作,

Dim objconnection As Object
Dim objRecordset As Object

答案 1 :(得分:0)

此过程使用Delphi XE2编写 它读取cvs字段并将其放入ADO表

procedure addRowsFromCVS(cvsFileName : string; tblDocumentiRighe: TADOTable);

var
  cvsFileToImport   : TStringlist;
  rowCount          : integer;
  fieldCount        : integer;
  fields            : TStrings;
  fieldValues       : TStrings;

  start             : integer;
  currentFieldName  : string;
  currentFieldValue : string;

begin
  // create memory string list
  cvsFileToImport := TStringlist.create;
  fields          := TStringlist.create;
  fieldValues     := TStringlist.create;

  // load rows from file
  cvsFileToImport.loadFromFile(cvsFileName);

  // split fields row
  split(';', cvsFileToImport[0], fields);

  // first field
  start := 0;

  // for all the rows
  for rowCount := 1 to cvsFileToImport.count - 1 do begin
    // start insert
    tblDocumentiRighe.insert;

    // get field values
    split(';', cvsFileToImport[rowCount], fieldValues);

    // ...
    for fieldCount := start to fieldValues.count - 1 do begin
      currentFieldName  := fields     [fieldCount];
      currentFieldValue := fieldValues[fieldCount];

      if currentFieldValue <> '' then begin
        tblDocumentiRighe.fieldByName(currentFieldName).asString := currentFieldValue;
      end;
    end;

    // post record
    tblDocumentiRighe.post;
  end;

  // free
  fieldValues    .free;
  fields         .free;
  cvsFileToImport.free;
end;