gayandnice
Technical User
- Mar 13, 2008
- 4
I need to read a csv file, the user selects the file from getfile, so I do NOT know the structure. Does anyone have sample code of reading a csv file into a cursor?
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
lcFileName = "NameOfCvsFile"
lcDelimiter = ","
*
* Open the file and read one line of data
lnHandle = FOPEN(lcFileName,0)
= FREAD(lnHandle) && Get rid of the header
lcString = FREAD(lnHandle) && First Data line
=FCLOSE(lnHandle)
*
* Find out the number of fields
lnLen = LEN(lcString)
lnFields = 1
FOR ii = 1 TO lnLen
IF SUBSTR(lcString,ii,1) = lcDelimiter
lnFields = lnFields + 1
ENDIF
ENDFOR
*
* Add one column for testing
lnFields = lnFields + 1
lcField = "CFIELD"+TRANSFORM(lnField)
*
* Build a table
CREATE TABLE CVSIMPORT FREE (CFIELD1 c(254))
USE CVSIMPORT EXCLUSIVE
FOR ii = 2 TO lnFields
lcRun = "ALTER TABLE CVSIMPORT ADD COLUMN CFIELD"+TRANSFORM(ii)+" c(254)"
&lcRun
ENDFOR
*
* Read in the data
APPEND FROM (lcFilename) TYPE CSV
BROWSE FOR !EMPTY(lcField)
*
* if any records show up in the browse window,
* the data you imported is not consistent in the number of fields or has commas inside the data
USE CVSIMPORT EXCLUSIVE
lnFields = FCOUNT()
DIMENSION laFields[lnFields,2]
FOR ii = 1 TO lnFields
laFields[ii,1] = ' '
laFields[ii,2] = 0
ENDFOR
*
SCAN ALL
FOR ii = 1 TO lnFields
laFields[ii,1] = FIELD(ii)
laFields[ii,2] = MAX(laFields[ii,2],LEN(ALLTRIM(FIELD(ii))))
ENDFOR
ENDSCAN
*
FOR ii = 1 TO lnFields
lcRun = "ALTER table CVSIMPORT ALTER COLUMN " + laFileds[ii,1] + " c(" + TRANSFORM(laFields[ii,2])+")"
&lcRun
ENDFOR