控件:OpenDialog1,ADOConnection,ADOQuery2
用ADOQuery来处理xls表里的数据,把它当成数据库一样地用SQL 语句来显示在grid里。
首先是要获取xls文件的路径名。
设置要打开的文件属性并过滤,并将获取的路径名放到EDIT框中。
OpenDialog1.filter:='Txt(*.xls)|*.xls';
OpenDialog1.defaultext:= '*.xls';
if OpenDialog1.Execute then
Edit9.text := OpenDialog1.FileName;
设置Adoquery1的connectionString=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=+路径名+;Extended Properties=Excel 8.0;Persist Security Info=Fals
所以,在button的事件中代码如下:
procedure TForm4.Button4Click(Sender: TObject);
var
str1,str2:String;
begin
OpenDialog1.filter:='Txt(*.xls)|*.xls';
OpenDialog1.defaultext:= '*.xls';
if OpenDialog1.Execute then
Edit9.text := OpenDialog1.FileName;
Adoquery1.Close;
Adoquery1.Connectionstring:='';
Str1:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source=';
str2:=';Extended Properties=Excel 8.0;Persist Security Info=False';
Edit10.Text:=Str1+Edit9.Text+Str2;
Adoquery1.Connectionstring:=Str1+Edit9.Text+Str2;
Adoquery1.close;
Adoquery1.sql.clear;
Adoquery1.sql.add('select * from [sheet1$]' );
Adoquery1.open;
end;
这样打开的xls文件里的sheet1表中的数据就显示在grid中了。