Delphi使用ADO读写Excel文件


本文整理自网络,侵删。

 
Delphi Ado读写Excel文件
Excel包含2003的*.xls格式、2007以上的*.xlsx格式文件
DbGrid标题、文本居中显示
测试环境
Delphi 10.3.3
Win10 专业版
主要代码

uses
 System.StrUtils;
 
procedure TForm1.Button1Click(Sender: TObject);
var
  SL: TStringList;
  i: integer;
begin
  if OpenDialog1.Execute then
    Edit1.Text := OpenDialog1.FileName;
  if Edit1.Text <> '' then
  begin
   ADOConnection1.Connected := False;
   if RightStr(Edit1.Text,1) = 's' then
   ADOConnection1.ConnectionString :=
    'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + Edit1.Text + ';Extended Properties=Excel 8.0' //如果是Excel2003 *.xls文件
   else
   ADOConnection1.ConnectionString :=
    'Provider=Microsoft.Ace.OLEDB.12.0;Data Source=' + Edit1.Text + ';Extended Properties=Excel 12.0'; //如果是Excel2007以上 *.xlsx文件
   ADOConnection1.Connected := True;
    try
      SL := TStringList.Create;
      ComboBox1.clear;
      ADOConnection1.GetTableNames(SL);
      for i := 0 to SL.Count - 1 do
      begin
        ComboBox1.Items.Add(SL.Strings[i])
      end;
      ComboBox1.ItemIndex:= 0;
    finally
      SL.Free;
    end;
  end;
end;
 
procedure TForm1.Button2Click(Sender: TObject);
 var
  i:integer;
begin
  if ComboBox1.Items.Count < 1 then
    exit;
  ComboBox1.ItemIndex:= 0;
  with ADOQuery1 do
  begin
    close;
    Connection := ADOConnection1;
    sql.clear;
    sql.Add('Select * from [' + ComboBox1.Items.Strings[ComboBox1.ItemIndex] + ']');
    open;
  end;
 
  for i := 0 to DBGrid1.Columns.Count -1 do
  begin
  DBGrid1.Columns[i].Width:=100;  //单元格宽度
  DBGrid1.Columns.Items[i].Title.Alignment:=taCenter; //表头居中
  DBGrid1.Columns.Items[i].Alignment:=taCenter; //文本居中
  end;
end;
 
procedure TForm1.FormCreate(Sender: TObject);
var
  SL: TStringList;
  i: integer;
begin
  Path := ExtractFilePath(Application.Exename);
  if FileExists(Path + 'Demo.xls') then
  begin
    Edit1.Text := Path + 'Demo.xls';
    ADOConnection1.ConnectionString :=
      'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + Edit1.Text +
      ';Extended Properties=Excel 8.0';
    try
      SL := TStringList.Create;
      ComboBox1.clear;
      ADOConnection1.GetTableNames(SL);
      for i := 0 to SL.Count - 1 do
      begin
        ComboBox1.Items.Add(SL.Strings[i])
      end;
      ComboBox1.ItemIndex:= 0;
    finally
      SL.Free;
    end;
  end;
end;

来源:https://www.amingstudio.com/delphi/663.html

相关阅读 >>

rad studio Delphi创建安卓服务creating android services

Delphi firedac 下的 sqlite [9] - 关于排序

Delphi 一行关键代码阻止360云查杀

Delphi研究之驱动开发篇(二)--工具及环境搭建

Delphi 字符串插入与删除

Delphi线程中关闭程序

Delphi使用zlib压缩和解压文件

Delphi 非主窗体(即子窗体)在任务栏显示按钮

Delphi createthread的线程传参数(小熊论坛的)

Delphi xe 制作的萤光时钟,可改作屏保

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...