delphi(stringgrid导出excel)
转载出处已忘记,请原谅。
需要uses Variants,ComObj
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;
try
XLApp := CreateOleObject('Excel.Application');
except
Exit;
end;
XLApp.WorkBooks.Add;
XLApp.SheetsInNewWorkbook := High(Args) + 1;
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;
调用方法:
ExportStrGridToExcel([StringGrid1]);
ExportStrGridToExcel([StringGrid1, StringGrid2]);