procedure SQLToExcel(DSN, einfuegeFeld, SQLtext:
string; Verbindung:boolean);
function Computername:
string;
var Buffer: PChar;
BufSize: DWord;
begin
Buffer := StrAlloc(256);
BufSize := 255;
if GetComputerName(Buffer, BufSize)
then
Computername := Buffer
else
Computername := '
';
StrDispose(Buffer);
end;
function Username:
string;
var Buffer: PChar;
BufSize: DWord;
begin
Buffer := StrAlloc(256);
BufSize := 255;
if GetUserName(Buffer, BufSize)
then
Username := Buffer
else
Username := '
';
StrDispose(Buffer);
end;
var Connection:
string;
pause, Sheet:variant;
i:word;
fehler:boolean;
flcid:Cardinal;
Excel:TExcelApplication;
begin
flcid:=Windows.GetUserDefaultLCID;
fehler:=false;
Excel:=TExcelApplication.Create(
nil);
try
try
Excel.Connect;
except
raise Exception.Create('
Auf diesem Rechner ist kein Excel installiert.');
fehler:=true;
end;
if not fehler
then begin
Excel.Visible[flcid]:=true;
Excel.Workbooks.Add(emptyParam, flcid);
Sheet:=Excel.ActiveSheet
as _WorkSheet;
Connection:=
'
ODBC;' +
'
DSN=' + DSN + '
;' +
'
Description=Test;' +
'
UID=' + Username + '
;' +
'
APP=Microsoft® Query;' +
'
WSID=' + Computername + '
;' +
'
Trusted_Connection=Yes';
pause:=false;
Sheet.QueryTables.add(
Connection, Sheet.Range[einfuegeFeld], SQLtext
).Refresh(pause);
if not Verbindung
then
for i:=Sheet.QueryTables.count
downto 1
do
Sheet.QueryTables[i].Delete;
Excel.Disconnect;
end;
finally
Excel.free;
end;
end;