Crash Course Delphi 16 [beta]:
|
Saving your data as a CSV file Saving your text database as a CSV file. (still to be polished and images to be added, but all source code has been tested) Setup of the projectWe'll continue with the Delphi project that we started in lesson 15. Open your project ParseCSV.dpr To MainMenu1, add an item in the MenuFile submenu:
AnalysisWhat should the OnClick event handler of FileSave do?
What should AddRecToList do with the row of a stringgrid?
|
procedure TForm1.FileSaveClick(Sender: TObject); var FileName1: string; Row: integer; begin ListBox1.Clear; // 1. clear listbox for Row := 0 to SG1.RowCount - 1 do // 2. for every record... // (row counting starts at 0!) AddRecToList(Row); // add to listbox // Use same filename as when loading. // For now, let's simply hard-code it. FileName1 := 'C:\ParseCSV\Office.csv'; ListBox1.Items.SaveToFile(FileName1); // 3. save as csv-file end;
The procedure AddRecToList should be declared under Private in the Interface section of the form:
private
procedure ParseRecord(sRecord: string; Row: integer);
procedure AddRecToList(Row: integer);
Here is the code that comes in the implementation part:
procedure TForm1.AddRecToList(Row: integer); var Col: integer; sField, sRecord: string; begin sRecord := ''; // 1. empty string Col := 0; // 2. start with column 0 repeat sField := SG1.Cells[Col, Row]; // 3. if (Pos(' ', sField) > 0) or (Pos(',', sField) > 0) then // 4. contains space or " ? sField := '"' + sField + '"'; sRecord := sRecord + sField; // 5. if Col < SG1.ColCount - 1 then // 6. more fields? sRecord := sRecord + ','; Col := Col + 1; // 7. next column until Col = SG1.ColCount; // 8. repeat if not done ListBox1.Items.Add(sRecord); // 9. end;