Crash Course Delphi 15 [beta]:
(Continued in Lesson 16)
|
Parsing a CSV file About loading and parsing a csv file (text still to be polished and images to be added, but all source code has been tested) Setup of the projectCreate a new directory, for example C:\ParseCSV 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 in directory C:\ParseCSV Partnumber,Article,Price,Stock
Set up a new Delphi project in C:\ParseCSV, with just one form, and save the project as ParseCSV.dpr Drop the following components on the form and set them up as follows:
|
What should the OnClick event handler of FileLoad do?
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.)
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).
procedure TForm1.FileLoadClick(Sender: TObject); var FileName1, sRecord: string; Row: integer; begin // Let user select a file. // Skip this until next lesson. For now, simply hard-code it. FileName1 := 'C:\ParseCSV\Office.csv'; ListBox1.Items.LoadFromFile(FileName1); // 2. SG1.RowCount := ListBox1.Items.Count; // 3. // for every record... ( count starts at 0 ! ) for Row := 0 to ListBox1.Items.Count - 1 do begin sRecord := ListBox1.Items[Row]; ParseRecord(sRecord, Row); // 4. end; // 5. Select first "data" cell SG1.Row := 1; SG1.Col := 0; SG1.SetFocus; end;
The procedure ParseRecord should be declared under Private in the Interface section
of
the
form:
private
procedure ParseRecord(sRecord: string; Row: integer);
procedure TForm1.ParseRecord(sRecord: string; Row: integer);
var
Col, PosComma: integer;
sField: string;
begin
sRecord := StringReplace(sRecord, '"', '',
[rfReplaceAll] ); // 1.
Col := 0; // first column of stringgrid
repeat
PosComma := Pos(',', sRecord); // 2.
if PosComma > 0 then
sField := Copy(sRecord, 1, PosComma - 1) // 3.a
else
sField := sRecord; // 3.b
SG1.Cells[Col, Row] := sField; // 4.
if PosComma > 0 then begin // 5.
Delete(sRecord, 1, PosComma);
Col := Col + 1; // next column
end;
until PosComma = 0; // 6.
end;
Finally, the code closing our application:
procedure TForm1.FileExitClick(Sender: TObject);
begin
Close; // close main window of application
end;