1

I have a Delphi application using DevExpress cxGrid (which is connected to database).

I require to be able to copy-paste data from Excel into the grid.

Is this possible? If so, how to do it, which additional components do i need?

SteveL
  • 309
  • 1
  • 5
  • 15

2 Answers2

2

Check the format with Clipboard.HasFormat(CF_TEXT).

Extract the text with Clipboard.AsText.

Split into rows with StringList.Text := Clipboard.AsText. Each item in the string list is now a row from the clipboard.

Split each row into individual cells using a Split function:

function Split(const s: string; Separator: char): TStringDynArray;
var
  i, ItemIndex: Integer;
  len: Integer;
  SeparatorCount: Integer;
  Start: Integer;
begin
  len := Length(s);
  if len=0 then begin
    Result := nil;
    exit;
  end;

  SeparatorCount := 0;
  for i := 1 to len do begin
    if s[i]=Separator then begin
      inc(SeparatorCount);
    end;
  end;

  SetLength(Result, SeparatorCount+1);
  ItemIndex := 0;
  Start := 1;
  for i := 1 to len do begin
    if s[i]=Separator then begin
      Result[ItemIndex] := Copy(s, Start, i-Start);
      inc(ItemIndex);
      Start := i+1;
    end;
  end;
  Result[ItemIndex] := Copy(s, Start, len-Start+1);
end;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    this can be achieved easier AND more elegant by using a TStringList and assigning the separator character, then set the length of the array to the count of the TStringList variable AND than just copy each item to it's corresponding string item in the array... or you could just access each item in the string list –  Dec 05 '10 at 12:48
  • @Dorin Duminica Excel data is 2D, won't your suggestion just flatten it into a 1D array? – David Heffernan Dec 05 '10 at 13:23
  • @Dorin Duminica I suspect you refer to Delimiter property, but that just won't work in general – David Heffernan Dec 05 '10 at 13:31
  • You may find that this Split function breaks when your cells contain tab characters because Excel would have to escape them somehow (probably with quotes around the cell). But you ought to be able to handle that easily enough if it becomes a problem. – David Heffernan Dec 05 '10 at 14:59
  • @Dorin Duminica yes indeed it does, although this is something of a non-sequiter – David Heffernan Dec 05 '10 at 15:39
0

You can check the content of the clipboard after you copy content from the Excel app. and then on CTRL+V shortcut you parse the content of the clipboard and set data to their respective cells.

  • Probably the easiest format to go for is to pull it out as text and stick it into a string list through the Text property. Each item in the list will be an entire row which you can then split apart into cells at column boundaries which are marked by ht tab characters. – David Heffernan Dec 05 '10 at 10:44