Load CSV Data into a StringGrid in Dephi

This short procedure will load data stored in a CSV file into a StringGrid in Dephi control for which can be used for display or processing.

By Tim Trott | Legacy Code | February 6, 2004

To use this code, simply call the method with the filename for the CSV and a reference to the StringGrid in Delphi and it will read the CSV data and populate the grid and headers.

pascal
procedure LoadCSV(Filename: string; sg: TStringGrid);
var
   i, j, Position, count, edt1: integer;
   temp, tempField : string;
   FieldDel: char;
   Data: TStringList;
begin
  Data := TStringList.Create;
  FieldDel := ',';
  Data.LoadFromFile(Filename);
  temp :=  Data[1];
  count := 0;
  for i:= 1 to length(temp) do
    if copy(temp,i,1) =  FieldDel then
      inc(count);
  edt1 := count+1;
  sg.ColCount := 30;
  sg.RowCount := Data.Count +1;
  sg.FixedCols := 0;
  for i := 0 to Data.Count - 1 do
    begin;
      temp :=  Data[i];
      if copy(temp,length(temp),1) <> FieldDel then
        temp := temp + FieldDel;
      while Pos('"', temp) > 0 do
        begin
          Delete(temp,Pos('"', temp),1);
        end;
      for j := 1 to edt1 do
      begin
        Position := Pos(FieldDel,temp);
        tempField := copy(temp,0,Position-1);
        sg.Cells[j-1,i+1] := tempField;
        Delete(temp,1,length(tempField)+1);
      end;
    end;
    Data.Free;
end;
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 3 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. BU

    On Thursday 2nd of February 2023, Budita said

    It works good. It would be much better if the column of StringGrid can be adjusted from automatically. But this one is great!

  2. MM

    On Wednesday 1st of February 2023, Mike McCarthy said

    Works great, just figuring out how to deal with new lines within a single collumn, otherwise it will not display correctly in the stringgrid. Removing that collumn everything works great, so minor hickup. Keep up the good work!

  3. MI

    On Wednesday 27th of November 2019, Miguel said

    Hi

    Thank you very interesting!!!

    Its possible download my sheet directly from google drive using stream?

    Thanks