当您从 Excel 复制到剪贴板时,剪贴板上会放置许多不同的格式。您需要找到可以复制的格式之一,这将产生所需的结果。
我过去实现这一点的方法是将 HTML 放在剪贴板上。您可以使用此功能:
procedure ClipboardError;
begin
raise EMyExceptionClass.Create('Could not complete clipboard operation.');
end;
procedure CheckClipboardHandle(Handle: Windows.HGLOBAL);
begin
if Handle=0 then begin
ClipboardError;
end;
end;
procedure CheckClipboardPtr(Ptr: Pointer);
begin
if not Assigned(Ptr) then begin
ClipboardError;
end;
end;
procedure PutInClipboard(ClipboardFormat: UINT; Buffer: Pointer; Count: Integer);
var
Handle: Windows.HGLOBAL;
Ptr: Pointer;
begin
if Count>0 then begin
Clipboard.Open;
Try
Handle := Windows.GlobalAlloc(GMEM_MOVEABLE, Count);
Try
CheckClipboardHandle(Handle);
Ptr := Windows.GlobalLock(Handle);
CheckClipboardPtr(Ptr);
Move(Buffer^, Ptr^, Count);
Windows.GlobalUnlock(Handle);
Clipboard.SetAsHandle(ClipboardFormat, Handle);
Except
GlobalFree(Handle);
raise;
End;
Finally
Clipboard.Close;
End;
end;
end;
var
HTMLClipboardFormat: UINT;
procedure PutHTMLInClipboard(Strings: TStrings);
var
Data: TStringList;
procedure WriteDescription(const StartOffset, EndOffset: Integer);
begin
while Data.Count<5 do begin
Data.Add('');
end;
Data[0] := 'Version:0.9';
Data[1] := Format('StartHTML:%.8d', [StartOffset]);
Data[2] := Format('EndHTML:%.8d', [EndOffset]);
Data[3] := Format('StartFragment:%.8d', [StartOffset]);
Data[4] := Format('EndFragment:%.8d', [EndOffset]);
end;
var
StartOffset, EndOffset: Integer;
Text: UTF8String;
begin
Data := TStringList.Create;
Try
WriteDescription(0, 0);//write out description stub - will be replaced later
StartOffset := Length(UTF8String(Data.Text));
Data.AddStrings(Strings);
EndOffset := Length(UTF8String(Data.Text))-1;
WriteDescription(StartOffset, EndOffset);//now we know the offsets we can write proper description
Text := Data.Text;
PutInClipBoard(HTMLClipboardFormat, PAnsiChar(Text), Length(Text));
Finally
FreeAndNil(Data);
End;
end;
....
initialization
HTMLClipboardFormat := Windows.RegisterClipboardFormat('HTML Format');
剩下的唯一事情就是生成您传递给该函数的 HTML。这取决于你。我建议您使用 Excel 将 HTML 放在剪贴板上,然后检查它生成的 HTML。将其用作您需要做的事情的指南。