1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| function ExportToExcelFile(Query: TDataSet; const AFilename:string) : Boolean;
var
Index : Integer;
XLApp, Sheet, Data, xlFile: OLEVariant;
_Col : Integer;
_Row : Integer;
RecNo : Integer;
function RangeRef(ACol, ARow, ACols, ARows:integer):string;
begin
ACol := Ord('A') + ACol - 1;
Result := Format('%s%d:%s%d',[
Chr(ACol),
ARow,
Chr(ACol + ACols - 1),
ARow + ARows - 1]);
end;
var
Records:integer;
VisCols: integer;
begin
Screen.Cursor:=crHourGlass;
Result:=False;
// On envoi l'entête dans la feuille
try
XLApp := CreateOleObject('Excel.Application');
XLApp.Visible := True;
xlFile := xlApp.Workbooks.Open(AFilename);
Sheet:= xlFile.Sheets['Feuil1'];
except on E:Exception do
begin
Data:=Unassigned;
MessageDlg('Impossible de trouver une instance de Microsoft Excel !',mtError,[mbOk],0);
Screen.Cursor:=crDefault;
Exit
end;
end;
Query.DisableControls;
// Query.FetchAll;
Query.First;
Records := Query.RecordCount;
VisCols := 0;
for Index:= 0 to Pred(Query.FieldCount) do
begin
if Query.Fields.Fields[Index].Visible then
Inc(VisCols);
end;
Data := VarArrayCreate([1, Records, 1, VisCols], varVariant);
for _Row := 1 to Records do
begin
_Col:=1;
for Index:=0 to Pred(Query.FieldCount) do
with Query.Fields.Fields[Index] do
if Visible then
begin
if (DataType = ftDate) or (DataType = ftDateTime) then
begin
if IsNull or (AsDateTime = 0) then
Data[_Row,_Col] := ''
else
Data[_Row,_Col] := AsDateTime;
end else
Data[_Row,_Col] := DisplayText;
Inc(_Col);
end;
Query.Next;
end;
try
Sheet.Range[RangeRef(1, 8, VisCols, Records)].Value := Data;
xlFile.Save
finally
Data:=Unassigned;
end;
Screen.Cursor:=crDefault;
if not VarIsEmpty(XLApp) then
begin
XLAPP := Unassigned;
Sheet := Unassigned;
xlFile := Unassigned;
end;
Query.EnableControls;
Result:=True;
end; |
Partager