Delphi 15 [beta]:
(Continued in Lesson 16)
CSV Files - part 2
Parsing a CSV file
About loading and parsing a csv file
Setup of the project
Create a small database to keep our stock of office material.
The file format should follow the rules as explained in lesson 14. Set up the following structure, either
with MS Excel (see last part of lesson 14) or with a text editor, and
save as Office.csv
- Each record is one line in the text file Office.csv
- The first record is a header record, containing the
field names. This is not needed by the rules for CSV, but it's easier
for knowing who's who :)
- The fields are separated by commas.
- Fields that contain spaces are delimited with
What should the OnClick event handler of FileLoad do?
- Let the user select a CSV file.
- Load the selected file into the listbox.
- Set the number of rows of the stringgrid equal to the number of
records. That is, the number of lines in the CSV file, thus: the number
of items in the listbox.
- Split up each item of the listbox into smaller strings, the field
values. The technical term is: we "parse" the record-strings. Next, put
every field value into the corresponding cell of the
stringgrid. For keeping with good modular coding practices, we'll
delegate these two tasks to a separate routine, that we named ParseRecord.
- Select the first "data" cell of the stringgrid at column 0 / row
What should ParseRecord do with a string (i.e. a record)
that it receives?
(To make things not too complicated, let's assume that there are
no double quotes nor commas embedded in the field values. In a next
version, we'll design a more complete algorithm.)
- Remove all the double quotes.
- Find the position of the first comma.
- Extract the first field value from the record-string.
- Put the field value in the corresponding cell of the stringgrid.
- If more fields, then delete from the record-string: the extracted
field plus its trailing comma.
- If more fields, then repeat from step (2).
And finally, the OnClick event handler of FileExit should simply
stop the application. As you remember, this is done by closing its main
window (its only window in this case).
As you see, we don't let the user select a file just yet, we hard coded
for one particular file. The file selection code is discussed in a next
Members of the DelphiLand Club
can access the full version of
our tutorials, including all fully commented source code files.
to become a DelphiLand Club member.
« Lesson 14 Lesson 16 »