用ExcelQueryTable必须在odbc 中设dsn
这是例子:
DSn为budget:
function Tauditdata.ToExcelFile(var Filename:OleVariant;SheetName:OleVariant;WIndowCaption:OleVariant;SqlStr:String):Boolean;
var
NewTemplate,ItemIndex
levariant;
CurSheet:_WorkSheet;
connectStr
levariant;
begin
NewTemplate:=emptyParam;
try
try
ExcelApp.Connect;
except
MessageDlg('您可能没有安装EXCEL', mtError, [mbOk], 0);
Abort;
end;
ExcelApp.visible[0]:=TRUE;
ExcelApp.Caption:=WindowCaption;
ExcelApp.Workbooks.Add(Newtemplate,0);
ExcelBook.ConnectTo(ExcelApp.workBooks.Item[1]);
ExcelBook.Title[0]:=WIndowCaption;
ExcelBook.Activate;
CurSheet:=ExcelBook.Sheets[1] as _worksheet;
CurSheet.Name:=SheetName;
connectstr := 'ODBC;DSN=budget;';
CurSheet.QueryTables.Add(connectstr,CurSheet.range['a3','e3'],SqlStr);
ExcelQueryTable.ConnectTo(CurSheet.QueryTables.Item(1));
ExcelQueryTable.Refresh;
except
on E: Exception do
begin
ItemIndex:=FALSE;
ExcelBook.Close(ItemIndex);
ExcelApp.Disconnect;
ExcelApp.Quit;
Application.MessageBox('数据输出到EXCEL过程出错,请检查EXCEL版本是否一致','警告',mb_ok);
exit;
end;
end;
ExcelQueryTable.Disconnect;
ExcelBook.Disconnect;
ExcelApp.Disconnect;
Result:=TRUE;
end;