function ExportStrGridToExcel(Args: array of const): Boolean;
var
iCount, jCount: Integer;
XLApp: Variant;
Sheet: Variant;
I: Integer;
begin
Result := False;
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
VarClear(XLApp);
end;
for I := Low(Args) to High(Args) do
begin
with TStringGrid(Args[I].VObject) do
begin
XLApp.WorkBooks[1].WorkSheets[I+1].Name := Name;
Sheet := XLApp.Workbooks[1].WorkSheets[Name];
for jCount := 0 to RowCount - 1 do
begin
for iCount := 0 to ColCount - 1 do
begin
Sheet.Cells[jCount + 1, iCount + 1] := Cells[iCount, jCount];
end;
end;
end;
end;
XlApp.Visible := True;
end;
调用方法如下:
procedure TForm1.Button6Click(Sender: TObject);
begin
ExportStrGridToExcel([StringGrid1]);