这是我将导出到EXCEL的函数打成DLL文件的函数:
Function ADOQueryToExcel(APPTitle:string;MyADOQuery:TADOQuery;MyXlsFileName:String):Boolean;stdcall;
var
Row,Col:integer;
MyExcelApp:Variant;
begin
if MyADOQuery.RecordCount=0 then
begin
Result:=False;
exit;
end;
try
MyExcelApp:=CreateOleObject('Excel.Application');
except
//application.Messagebox('无法打开Xls文件,请确认已经安装EXCEL.','',mb_OK+mb_IconStop);
//这句不能用,不知道为什么,必须使用Windows模块中的messagebox函数来返回信息
MessageBox(0,'请确认已经安装EXCEL',pchar(APPTitle),MB_ok);
Result:=False;
Exit;
end;
try //(2)try..except...end开始
try //(3)try..except...end开始
MyExcelApp.Caption := '应用程序调用 Microsoft Excel: '+APPTitle;
MyExcelApp.Visible := True;
MyExcelApp.WorkBooks.Add; //添加新工作簿:
MyExcelApp.WorkSheets[1].name:=APPTitle;
MyExcelApp.WorkSheets[1].Activate;
MyExcelApp.Cells[1,1]:=APPTitle; //设置表格的大标题名
MyExcelApp.ActiveSheet.Rows[1].RowHeight := 1/0.035; // 设置高度为1厘米
//导出标题开始
MyExcelApp.Cells[2,1]:='序号';
MyExcelApp.ActiveWorkbook.ActiveSheet.Columns[1].ColumnWidth:=8;//设置列宽
for Col:=1 to MyADOQuery.FieldCount do
begin
MyExcelApp.ActiveWorkbook.ActiveSheet.Columns[col+1].ColumnWidth:=10;//设置列宽
MyExcelApp.Cells[2,col+1]:=MyADOQuery.Fields[col-1].FieldName;
end;
//导出数据开始
for Row:=1 to MyADOQuery.RecordCount do
begin
MyExcelApp.ActiveSheet.Rows[Row+2].RowHeight := 1/0.07; // 设置高度为0.5厘米
MyExcelApp.ActiveSheet.Rows[Row+2].Font.Color := clBlue;
MyExcelApp.Cells[Row+2,1]:=row;
MyExcelApp.ActiveWorkbook.ActiveSheet.Rows[Row].HorizontalAlignment:=1;
//左对齐方式1 居中对齐:-4108:
for Col:=1 to MyADOQuery.FieldCount-1 do
MyExcelApp.Cells[Row+2,col+1]:=MyADOQuery.Fields[Col-1].asstring;
MyADOQuery.next;
end;
//导出数据结束
//保存文件前查找文件是否在,在就删除该文件
if FileExists(MyXlsFileName) then
Begin
deletefile(MyXlsFileName);
end;
MyExcelApp.ActiveWorkbook.saveas(MyXlsFileName);
//MyExcelApp.ActiveWorkbook.close; //关闭工作簿,在EXCEL关闭的情况下将出现异常,
MyExcelApp.Quit; //退出 Excel
MyExcelApp:=Unassigned; //释放VARIANT变量
MessageBox(0,'数据导出时发生错误!',pchar(APPTitle),MB_ok);
Result:=true;
except
MessageBox(0,'数据导出时发生错误!',pchar(APPTitle),MB_ok);
Result:=false;
end;//(2)except结束
finally
MessageBox(0,'数据导出时发生错误!',pchar(APPTitle),MB_ok);
//MyExcelApp.ActiveWorkbook.close;
MyExcelApp.quit;
MyExcelApp:=Unassigned; //释放VARIANT变量
end; //(3)except结束
if not Result then
MessageBox(0,'数据导出时发生错误!',pchar(APPTitle),MB_ok);
end; //导出函数结束
自己看吧