Submitted by st on
Une petite classe qui permet lire les données depuis le fichier au format CSV (comma-separated values). Les caractéristiques :
- Fichiers ANSI uniquement (actuellement)
- Support de valeurs de multiples lignes
- Analyse intelligente des valeurs numériques (entiers, flottant, decimales) afin d'éviter les erreurs de conversion en différentes locales
- Paramétrisation : la taille du tampon, le caractère de délimitation
Voici un exemple du fichier CSV accepté.
1,12.345, 3.3 , "55,55" 25, 45, 45.65 , Some text 77 ,11.1, 0.5 8. ,.6, 6.8E01, "Comment ""line 4""" , "Hello, CSV" 0 ,.0, 0.0E01, "Multi line text line 2 line 3"
Voici une exemple d'utilisation.
procedure ReadExemple; var CSV: TA4CSVRead; Row, Col: integer; SumCol0, SumCol1, SumCol2: double; begin SumCol0 := 0; SumCol1 := 0; SumCol2 := 0; CSV := TA4CSVRead.Create('test.csv'); try CSV.ReadFile; for Row := 0 to CSV.RowsCount - 1 do begin Write('Row ', Row, ':|'); for Col := 0 to CSV.ColsCount(Row) - 1 do begin Write(Format('%s|', [CSV.GetValue(Row, Col)])); end; writeln; SumCol0 := SumCol0 + CSV.GetDouble(Row, 0); SumCol1 := SumCol1 + CSV.GetDouble(Row, 1); SumCol2 := SumCol2 + CSV.GetDouble(Row, 2); end; Writeln('Sum(col0) = ', SumCol0); Writeln('Sum(col1) = ', SumCol1); Writeln('Sum(col2) = ', SumCol2); finally CSV.Free; end; end;
Exemple de lecture ligne par ligne
procedure ExempleReadRowByRow; var CSV: TA4CSVRead; Col: integer; SumCol0, SumCol1, SumCol2: double; begin SumCol0 := 0; SumCol1 := 0; SumCol2 := 0; CSV := TA4CSVRead.Create('test.csv'); try while CSV.ReadRow do begin for Col := 0 to CSV.ColsCount(0) - 1 do Write('%s|', CSV.GetValue(0, Col)); Writeln; SumCol0 := SumCol0 + CSV.GetDouble(0, 0); SumCol1 := SumCol1 + CSV.GetDouble(0, 1); SumCol2 := SumCol2 + CSV.GetDouble(0, 2); end; Writeln('Sum(col0) = ', SumCol0); Writeln('Sum(col1) = ', SumCol1); Writeln('Sum(col2) = ', SumCol2); finally CSV.Free; end; end;
Récupérer le module : a4csvtools.pas