1

我目前正在尝试稍微修改本教程,将 Excel 文件加载到 Delphi 中。我想使用 OpenDialog 来获取文件路径并启动后续程序,将文件加载到文本框并启动连接程序。我起草了下面的代码,但注意到在编译文件并单击按钮后会发生。我的理解是单击按钮应该显示打开的文件窗口。我不明白为什么带有文件选择的窗口没有出现。

procedure TForm1.Button1Click(Sender: TObject);
var
  openDialog : TOpenDialog;    // Open dialog variable
  strConn : WideString; // Declare wide string for the connection

begin
  // Create the open dialog object - assign to our open dialog variable
  openDialog := TOpenDialog.Create(self);

  // Set up the starting directory to be the current one
  openDialog.InitialDir := GetCurrentDir;

  // Only allow existing files to be selected
  openDialog.Options := [ofFileMustExist];

  // Allow only .Excel and .pas files to be selected
  openDialog.Filter :=
    'Excel 2003|*.xls|Excel 2007 and newer|*.xlsx';

  // Select pascal files as the starting filter type
  openDialog.FilterIndex := 2;

  // Give file path to the edit
  Edit1.Text := openDialog.FileName;


  // Connect the Excel file
  AdoConnection1.Connected:=False;
  AdoConnection1.ConnectionString:=strConn;

  end;
4

1 回答 1

2

您未能显示对话框。像这样做:

if not openDialog.Execute then
  Abort;

显然,您需要在初始化属性之后但在读取文件名之前执行此操作。

从这个早先的问题中可以看出,您之前显然已经成功地做到了这一点。正如我之前所说,将选择文件名的代码与其余代码分开是一个非常好的主意。尝试安排代码部分执行一项任务,并且单独执行一项任务。这样做可以使这些代码段可组合。

于 2014-07-03T14:03:38.203 回答