delphiexceldevexpresscopy-pastequantumgrid

How to paste data from Excel into cxGrid


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?


Solution

  • 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;