不管是StringGrid还是TAdvStringGrid,都没有像DBGrid那样方便的复制、分列分行、单元格合并功能。那么,怎么对StringGrid所选的数据进行复制,然后粘贴到其他文件中?
一、环境
- Windows10
- RAD Studio 10 Seattle
- SQL Server 2014 Management Studio
二、Clipboard的使用
在uses处引用Clipbrd,才能相应使用Clipboard
1、OnSelectCell
单击单元格时触发的事件。
原本是用的OnSelectCell事件,但是发现怎么都获取不到准确的被选中的数据,而且每次获取到的数据都是没有没有规律的。
OnSelectCell事件只适用于单选某一个单元格的事件触发。
procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;var CanSelect: Boolean);
begin
Clipboard.Clear;
clipboard.Open;
Clipboard.asText:= StringGrid1.cells[ACol,ARow];//当前选中的单元格
Clipboard.Close;
end;
- 运行
单选一个单元格,CTRL+C,CTRL+V到excel。
2、OnDrawCell
单元格的绘画。
然后又换了OnDrawCell,但是发现会频繁地出现剪贴板拒绝访问的弹窗。pass
3、OnMouseUp
鼠标放开时触发的事件。
还有一个对应的OnMouseMove(鼠标按下时触发的事件)。
最后,在百度之下,从这篇文章【在Delphi TStringGrid中检测单个或多个选择】中发现了让我豁然开朗的解析。
在OnMouseUp事件中,可以准确地铺捕获Selection的Top 、Bottom 、Left 、Right。
procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);
var
i, j: Integer;
s: string;
begin
Clipboard.Clear; //清除剪贴板的内容
Clipboard.Open; //剪贴板打开
with StringGrid1 do
for i := Selection.Top to Selection.Bottom do //被选择的内容最上到最下
begin
for j := Selection.Left to Selection.Right do //被选择的内容最左到最右
begin
s := s + Cells[j, i] +#9; //#9,在excel中分列
end;
s:=s+#13; //#13,在excel中分行
end;
Clipboard.AsText := s; //剪贴板内容获取
clipboard.Close; //剪贴板关闭
end;
- 运行
三、结束
- 其他
如果是用的TAdvStringGrid控件的话,它本身有一个OnSelectionChanged事件,可以看它的参数,本身就包含了ALeft, ATop, ARight, ABottom,所以如果用TAdvStringGrid控件的话,在OnSelectionChanged事件中直接用Clipboard剪贴板即可。
procedure Tform_geoponics_build_report.gridSelectionChanged(Sender: TObject;ALeft, ATop, ARight, ABottom: Integer);
至此,【Delphi】Clipboard,剪贴板获取StringGrid所选的数据复制粘贴的记录,打板!