Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing CSV files into individual fields

Status
Not open for further replies.

beetlejoose

Programmer
Aug 15, 2010
2
0
0
GB
The following procedure parses a record from a .csv file and passes back the fields read in the Strings parameter.
This works with .csv files exported from Excel etc. Null fields, fields containing comma's and double quotes etc are all parsed correctly.

procedure ReadCSVRecord(var CSVFile : TextFile; Strings : TStrings);
var P : PChar;
Line, Field : string;
Quote : boolean;
begin
ReadLn(CSVFile, Line);
Strings.Clear;
if length(Line) > 0 then
begin
P := @Line[1];
repeat
Field := '';
if P^ = '"' then
begin
Inc(P);
repeat
while P^ <> '"' do
begin
Field := Field + P^;
Inc(P);
end;
Quote := False;
while P^ = '"' do
begin
Inc(P);
if Quote then Field := Field + '"';
Quote := not Quote;
end;
until (P^ = #0) or Quote;
end
else
begin
while (P^ <> #0) and (P^ <> ',') do
begin
Field := Field + P^;
Inc(P);
end;
end;
Strings.Add(Field);
if P^ = #0 then exit;
Inc(P);
until P^ = #0;
Strings.Add('');
end;
end;
 
Instead of writing your own code, why not use the, possibly little known, CommaText property of TStrings?

An example of using CommaText is shown below.
Code:
var
  s: TStringList;
begin
  s := TStringList.Create;
  try
    s.CommaText := 'a, b, "c,d"';
    ShowMessage( s[0] );
    ShowMessage( s[1] );
    ShowMessage( s[2] );
  finally
    s.Free;
  end;
end;
Will Display
as the output of the three ShowMessage calls.

Andrew
Hampshire, UK
 
Don't forget that you can use the TStringList.LoadFromFile method to read an entire text file into the list in one command.

And if your your text file uses something other than commas as delimiters, you can still use the DelimitedText and Delimiter properties of TStringList to provide fields in the same way.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top