Please enable JavaScript to view this site.

Codolex

The CSV Import activity can be used to import entities directly from a csv file

Uses System.Classes.TStringList

Uses System.IOUtils.TFile.ReadAllLines

 

CSVImport

Activity properties

 

var ProductsList: ICodolexList<HelpAndManualScreenshots.DataSource.Codolex.IProducts>;

var CSVLines := TFile.ReadAllLines(ImportFileName);

 

var ColumnList := TStringList.Create;

try

   ColumnList.Delimiter := ',';

   ColumnList.StrictDelimiter := True;

   ColumnList.DelimitedText := CSVLines[0];

  for var ColumnIndex := 0 to ColumnList.Count -1 do

     ColumnList[ColumnIndex] := Trim(ColumnList[ColumnIndex]);

   

   ProductsList := TCodolexList<HelpAndManualScreenshots.DataSource.Codolex.IProducts>.Create;

   

  var IsFirstLine := True;

  for var Line in CSVLines do

  begin

    if IsFirstLine then

    begin

       IsFirstLine := False;

       Continue;

    end;

     

    var Values := Line.Split([',']);

    var CSVEntity: HelpAndManualScreenshots.DataSource.Codolex.IProducts;

     CSVEntity := HelpAndManualScreenshots.DataSource.Codolex.TProducts.Create;

    var FieldCount := Length(Values);

     

    var FieldPos := ColumnList.IndexOf('ProductID');

    if (FieldPos > -1) and (FieldPos < FieldCount) then

       CSVEntity.ProductID := Values[FieldPos].ToInteger;

     

     ...

     

     FieldPos := ColumnList.IndexOf('Discontinued');

    if (FieldPos > -1) and (FieldPos < FieldCount) then

       CSVEntity.Discontinued := Values[FieldPos];

     

     ProductsList.Add(CSVEntity);

  end;

finally

   ColumnList.Free;

end;

Resulting code

 

The separator value is a ',' by default, but can be changed to other separators like ';'.

 

The associations of entities are not included in the import, the association can be set after an import with id value.

 

 

© by GDK Software