我試圖使用TOpenDialog將路徑傳遞給AdoConection,並將Excel文件的內容加載到表中。我目前正在嘗試下面的代碼,但代碼的最後一部分沒有連接到Excel,返回錯誤: [dcc32錯誤] sample_map.pas(80):E2010不兼容的類型:'string'和'TOpenDialog'在Delphi中將文件路徑從TOpenDialog傳遞爲字符串
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 .dpr and .pas files to be selected
openDialog.Filter :=
'Excel 2003 and older|*.xls|Excel 2007 and older|*.xlsx';
// Select pascal files as the starting filter type
openDialog.FilterIndex := 2;
// Display the open file dialog
if openDialog.Execute
then ShowMessage('File : '+openDialog.FileName)
else ShowMessage('Open file was cancelled');
// Free up the dialog
openDialog.Free;
// Connect the Excel file
strConn:='Provider=Microsoft.Jet.OLEDB.4.0;' +
'Data Source=' + openDialog + ';' +
'Extended Properties=Excel 8.0;';
AdoConnection1.Connected:=False;
AdoConnection1.ConnectionString:=strConn;
end;
是的,這裏的關鍵是在將所選文件名添加到連接字符串時,您錯過了Filename屬性。 –