Sunday, October 26, 2008

How to connect a csv file to Delphi

Can a comma delimited file, (*.csv) be viewed through delphi? If so, what components, settings, and code are used?



If you just want to view the text, drop a memo onto a form and call

memo1.Lines.LoadFromFile( 'c:\mycsv.csv');

Another option maybe you want to load it into a stringgrid

var
i, j: integer;
slFile, sl: TStringList;
begin
try
slFile := TStringList.Create;
slFile.LoadFromFile( 'c:\mycsv.csv');

with stringgrid1 do
try
rowcount := slFile.Count;
FixedCols := 1;
FixedCols := 0;

for i := 0 to slFile.count - 1 do
begin
sl := TStringList.Create;
sl.Delimiter := ',';
sl.DelimitedText := slFile.strings[ i];

for j := 0 to sl.count - 1 do
Cells[ j, i+1] := sl.Strings[ j];
end;
finally
freeAndNil( sl)
end;
finally
freeAndNil( slFile)
end;
end;

rowcount := slFile.Count;
should probably be rowcount := slFile.Count+1 to allow for header row

source : http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_22904840.html

No comments: