Mirror

Copy selected data from a TStringGrid to the clipboard (Views: 102)


Problem/Question/Abstract:

I have various TStringGrid objects within my application and I want to allow the user to copy selected data to the clipboard for insertion into other programs such as Excel.

Answer:

Solve 1:

var
  S: string;
  i, k: Integer;
begin
  S := EmptyStr;
  with StringGrid1 do
  begin
    for i := FixedRows to RowCount - 1 do
    begin
      for k := FixedCols to ColCount - 1 do
      begin
        if k > FixedCols then
          S := S + #9;
        S := S + Cells[k, i];
      end;
      S := S + #13#10;
    end;
  end;
  Clipboard.AsText := S;

This generates a string in which columns are separated by Tab characters and rows by CR/LF linebreaks. Most spreadsheets are able to paste this into cells correctly.

Same for the selection in a grid:

S := '';
with grid do
  for i := Selection.Top to Selection.Bottom do
  begin
    for k := Selection.Left to Selection.Right do
    begin
      S := S + Cells[k, i];
      if k <> Selection.Right then
        S := S + #9;
    end;
    S := S + #13#10;
  end;
Clipboard.AsText := S;


Solve 2:

Here is how you can copy a selection.

uses
  ClipBrd;

procedure CopyGridSelectionToClipBoard(Grid: TStringGrid; Selection: TGridRect);
const
  TAB = Chr(VK_TAB);
  CR = #13;
var
  r, c: integer;
  S: string;
begin
  S := '';
  for r := Selection.Top to Selection.Bottom do
  begin
    for c := Selection.Left to Selection.Right do
    begin
      S := S + Grid.Cells[c, r];
      if c < Selection.Right then
        S := S + TAB;
    end;
    if r < Selection.Bottom then
      S := S + CR;
  end;
  ClipBoard.SetTextBuf(PChar(S));
end;

Pasting would be the reverse. An idea would be to get the text from the clipboard and assign it to a TStringList. This way you'll know how many rows you have.

var
  F: TStringList;
begin
  F := TStringList.Create;
  F.Text := Clipboard.AsText;
  F.Free;
end;

You'll still need to parse each row to get the columns.

By the way, you can use the text you copied with the above procedure to paste into Excel. Excel knows how to parse it if you use the TAB to delimit columns.

<< Back to main page