Crash Course Delphi 15 [beta]:
CSV Files - part 2

(Continued in Lesson 16)


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

Partnumber,Article,Price,Stock
12005A,Calculator,20.49,26
12005B,"Calculator Pro",30.49,10
12006A,PC,990.00,6
12007A,Scanner,349.49,7

  • 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 double-quotes.

Analysis

What should the OnClick event handler of FileLoad do?

  1. Let the user select a CSV file.
  2. Load the selected file into the listbox.
  3. 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.
  4. 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.
  5. Select the first "data" cell of the stringgrid at column 0 / row 1.

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.)

  1. Remove all the double quotes.
  2. Find the position of the first comma.
  3. Extract the first field value from the record-string.
  4. Put the field value in the corresponding cell of the stringgrid.
  5. If more fields, then delete from the record-string: the extracted field plus its trailing comma.
  6. 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 lesson.


Members of the DelphiLand Club can access the full version of our tutorials, including all fully commented source code files.

Click here to become a DelphiLand Club member.

 Lesson 14  Lesson 16