Re: Copying data from a StringGrid

Posted by Johan p14205 on April 14, 2007

In Reply to Copying data from a StringGrid posted by Ken on April 06, 2007

I've found some code to copy data from a stringgrid to Excel but it's too complicated for me. Could anyone help me copy data from stringgrid cells using the cut function which I can then paste into an excel document?

Let's say that you want to copy the contents of all the cells of a Delphi stringgrid to an Excel spreadsheet. The easiest way is the following source code, that copies everything to Windows' clipboard. Next you can paste it manually to the spreadsheet (click on the first cell of a block in Excel that is large enough and press Ctrl+V).

procedure TForm1.Button1Click(Sender: TObject);
const
  TAB = #9;
  CR = #13;
var
  R, C: integer;
  S: string;
begin
  S := '';
  for R := 0 to Grid.RowCount - 1 do begin
    for C := 0 to Grid.ColCount - 1 do begin
      S := S + Grid.Cells[C, R];
      if C < Grid.ColCount - 1 then S := S + TAB;
    end;
    if R < Grid.RowCount - 1 then S := S + CR;
  end;
  Clipboard.AsText := S;
end;

Related articles

       

Follow Ups