我想按照此处示例项目中的建议将 CSV 文件读取到 Delphi (DBGrid) 。我有一个简单的表单,我在其中定义了 TOpenDialog 和 TCsvTransform 中的元素。当我尝试创建一个将文件路径从 TOpenDialog 传递给负责读取 CSV 文件的过程时,该项目无法编译。
procedure ReadCSVFile;
var
SS: TStringStream;
OS: TFileStream;
begin
OS := TFileStream.Create(MainOpenDialog.FileName, fmCreate);
SS := TStringStream.Create;
try
ClientDataSet1.SaveToStream(SS, dfXML);
with TCsvTransform.Create do
try
Transform(DPToCsv, SS, TStream(OS));
finally
Free;
end;
finally
SS.Free;
OS.Free;
end;
end;
编译器说MainOpenDialog未声明。完整的代码,我认为我在其中声明了 Open Dialog 元素,如下所示。
unit geoimp;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.Buttons, Vcl.StdCtrls,
Vcl.Grids, Vcl.DBGrids, Data.DB, Datasnap.DBClient, ShlObj;
const
shfolder = 'ShFolder.dll';
type
TMainForm = class(TForm)
MainPageControl: TPageControl;
ImportTab: TTabSheet;
MapPreviewTab: TTabSheet;
GeoMatchingTab: TTabSheet;
ImportDBGrid: TDBGrid;
ImportLbl: TLabel;
SlctImportDta: TSpeedButton;
MainClientData: TClientDataSet;
MainDataSource: TDataSource;
MainOpenDialog: TOpenDialog;
procedure SlctImportDtaClick(Sender: TObject);
procedure ReadCSVFile;
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure ReadCSVFile;
var
SS: TStringStream;
OS: TFileStream;
begin
OS := TFileStream.Create(MainOpenDialog.FileName, fmCreate);
SS := TStringStream.Create;
try
ClientDataSet1.SaveToStream(SS, dfXML);
with TCsvTransform.Create do
try
Transform(DPToCsv, SS, TStream(OS));
finally
Free;
end;
finally
SS.Free;
OS.Free;
end;
end;
procedure TMainForm.SlctImportDtaClick(Sender: TObject);
begin
// Create the open dialog object - assign to our open dialog variable
MainOpenDialog := TOpenDialog.Create(self);
// Set up the starting directory to be the current one
MainOpenDialog.InitialDir := GetCurrentDir;
// Only allow existing files to be selected
MainOpenDialog.Options := [ofFileMustExist];
// Allow only .dpr and .pas files to be selected
MainOpenDialog.Filter :=
'CSV Files|*.csv';
// Select pascal files as the starting filter type
MainOpenDialog.FilterIndex := 2;
// Display the open file dialog
if MainOpenDialog.Execute
then ShowMessage('File : '+MainOpenDialog.FileName)
else ShowMessage('Open file was cancelled');
// Free up the dialog
MainOpenDialog.Free;
end;
end.