Friday, December 24, 2010

Import CSV into QTP Datatable

'************************************************************
Function ImportCsvFiletoDatatable(CsvFilePath,SheetName,HeaderDelimiter)
Dim filePath
Dim fso
Dim f
Dim fData
Dim arrData
Dim CsvValue
Dim CsvSheet
Dim CsvFirstLine
Dim CsvColumns
Dim ColumnIndex
Dim rIndex
Dim cIndex
 
filePath=CsvFilePath    'Specify file Path
 
'Open CSV File using File System Object
Set fso=createobject("scripting.filesystemobject")
Set f  = fso.OpenTextFile(filePath)
 
CsvFirstLine=f.readline    'Treating like first line is the column names
 
CsvColumns=split(CsvFirstLine,HeaderDelimiter)    'Split the line using HeaderDelimiter
 
Set CsvSheet=DataTable.GetSheet(SheetName)    'Get the Specified sheet
 
'Add the splitted values as Datatable Columns
For ColumnIndex=lbound(CsvColumns)  to ubound(CsvColumns)
CsvSheet.addparameter CsvColumns(ColumnIndex),""
Next
 
 
While not f.AtEndOfStream
 
rIndex=f.Line-1    'Specify Row index
fData=f.ReadLine    ' Read CSV File Line
arrData=split(fData,",")    'Split the line
cIndex=1    'Specify Column Index
CsvSheet.SetCurrentRow(rIndex)    'Set Row in the Datatable
 
' Add values in Datatable
For Each CsvValue In arrData
CsvSheet.getparameter(cIndex).value=CsvValue
cIndex=cIndex+1
Next
 
Wend
 
f.Close
Set fso=Nothing
 
End Function
'************************************************************
 
'Calling this Function
ImportCsvFiletoDatatable "C:\Sample.csv","Action1","," 

No comments:

Post a Comment