Crash Course Delphi 16 [beta]:
CSV Files - part 3


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 project

We'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:

  • Caption: &Save
  • Name: FileSave

Analysis

What should the OnClick event handler of FileSave do?

  1. Clear the listbox.
  2. Make a record-string out of each row of the stringgrid and add it to the listbox. For keeping with good modular coding practices, we'll delegate these two tasks to a separate routine, that we named AddRecToList.
  3. Save the listbox contents to a file, with the same name as from which it was loaded initially.

What should AddRecToList do with the row of a stringgrid?

  1. Start with an empty record-string.
  2. Start at column number 0 of the current row.
  3. Get the contents of the current cell into a variable for the field value.
  4. If the field contains a space or a comma, put double quotes around it.
  5. Add the field to the record-string.
  6. If more fields, then add a comma to the record-string
  7. Increment the column-counter.
  8. If more fields, repeat from step (3).
  9. When done with all the fields, add the record-string to the listbox.

Let's code

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;

« Lesson 15   Lesson 17 »     Top