如何使用Delphi将Access数据库导出到Excel

时间:2012-05-08 09:58:55

标签: delphi excel-2007 delphi-xe2

我正在使用Delphi编写数据库应用程序,需要将数据从访问数据库导出到Excel电子表格。我可以使用docmd.spreadsheet管理相反的顺序(导入excel来访问)。 100%工作。但我不知道如何设置导出参数。我需要帮助。

1 个答案:

答案 0 :(得分:4)

检查此示例代码,我也建议您阅读DoCmd.TransferSpreadsheet Method文档。

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj;

procedure ExportDataAccess(const AccessDb, TableName, ExcelFileName:String);
Const
  acQuitSaveAll             = $00000001;
  acExport                  = $00000001;
  acSpreadsheetTypeExcel9   = $00000008;
  acSpreadsheetTypeExcel12  = $00000009;
var
 LAccess : OleVariant;
begin
 //create the COM Object
 LAccess := CreateOleObject('Access.Application');
 //open the access database
 LAccess.OpenCurrentDatabase(AccessDb);
 //export the data
 LAccess.DoCmd.TransferSpreadsheet( acExport, acSpreadsheetTypeExcel9, TableName, ExcelFileName, True);
 LAccess.CloseCurrentDatabase;
 LAccess.Quit(1);
end;

begin
 try
    CoInitialize(nil);
    try
      ExportDataAccess('C:\Datos\Database1.accdb','Sales','C:\Datos\MyExcelFile.xls');
      Writeln('Done');
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.