ADO读取EXCEL
窗体上拖放ADOQuery1,DataSetProvider1,DataSource1,ClientDataSet1,OpenDialog1,
ExcelApplication1,ExcelWorkbook1,ExcelWorksheet1控件。
Function TForm1.ADOOpenExls:Boolean;
var
connstr,FirstSheetName: String;
begin
// ADO读取EXCEL文件方法.
Result := False;
DataSetProvider1.DataSet := ADOQuery1;
DataSource1.DataSet := ClientDataSet1;
try
OpenDialog1.Filter := 'Excel文档(*.xlsx)|*.xlsx|Excel文档(*.xls)|*.xls';
OpenDialog1.InitialDir := 'C:\';
OpenDialog1.Title := '选择导入Excel文件' ;
OpenDialog1.DefaultExt := 'xlsx';
if OpenDialog1.Execute then
begin
ExcelApplication1.Connect;
ExcelApplication1.Caption := 'App Import Excel';
ExcelApplication1.Workbooks.Open(OpenDialog1.FileName,False,
False,EmptyParam,EmptyParam,EmptyParam,True,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,0);
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks[1]);
ExcelWorksheet1.ConnectTo(ExcelWorkbook1.Sheets[1] as _WorkSheet);
//EXCEL文件的第一个SHEET表单名称.
FirstSheetName := ExcelWorksheet1.Name;
//关闭Excel文件.
ExcelWorkbook1.Close;
ExcelApplication1.Quit;
ExcelApplication1.Disconnect;
with ADOQuery1 do
begin
Close;
connstr := 'Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;'
+'Data Source=%s;Persist Security Info=False;';
connstr := Format(connstr, [OpenDialog1.FileName]);
ConnectionString := connstr;
SQL.Clear;
//Sheet名称后缀必须添加$.
SQL.Add(Format('SELECT * FROM [%s$]',[FirstSheetName]));
Open;
ClientDataSet1.Close;
ClientDataSet1.Fields.Clear;
ClientDataSet1.Data := DataSetProvider1.Data;
Close;
{
cxGrid1DBTableView1.DataController.DataSource := DataSource1;
cxGrid1DBTableView1.ClearItems; //在GRID中展示数据.
cxGrid1DBTableView1.DataController.CreateAllItems(True);
cxGrid1DBTableView1.ApplyBestFit();
}
Result := True;
end;
end;
except
ON E :Exception do
begin
ADOQuery1.Close;
ExcelApplication1.Quit;
ExcelApplication1.Disconnect;
ShowMessage(E.Message);
end;
end;
end;