DC娱乐网

Excel交互式动态切换导航条(Delphi版本

前言

之前跟大家分享过用C#制作的Excel动态导航条小工具。

今天再给大家分享一下用Delphi实现的导航条小工具,可以同时兼容微软Excel和WPS版本的Excel。

界面设计

界面跟C#版本的导航条小工具类似。

功能简述

左边列表框:展示当前打开的Excel工作簿,点击后激活对应的工作簿

右边列表框:展示选定工作簿里面的worksheet,点击后即会对应的工作表

底部按钮: 获取当前打开的Excel工作簿,并添加到左边的列表框

Delphi实现

使用OleObject操作Excel,只需要电脑上安装有Excel或者WPS即可。

unit wps_app;interfaceuses  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ComObj;type  TfrmNav = class(TForm)    Test: TButton;    lbExcels: TListBox;    lbSheets: TListBox;    Label1: TLabel;    Label2: TLabel;    procedure TestClick(Sender: TObject);    function GetOpenedExcel: Variant;    procedure lbExcelsClick(Sender: TObject);    procedure lbSheetsClick(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  frmNav: TfrmNav;implementation{$R *.dfm}procedure TfrmNav.lbExcelsClick(Sender: TObject);var  wps, wb: Variant;  I, j: Integer;begin  if lbExcels.ItemIndex = -1 then exit;  wps := GetOpenedExcel;  if varisempty(wps) then  begin    lbExcels.Clear;    exit;  end;  if wps.workbooks.count = 0 then   begin    lbExcels.Clear;    exit;  end;    //  lbSheets.Clear;  for I := 1 to wps.workbooks.count do  begin    wb := wps.workbooks[I];    if wb.Name = lbExcels.Items[lbExcels.ItemIndex]	then    begin      wb.activate;      for j := 1 to wb.worksheets.count do      begin        lbSheets.Items.Add(wb.worksheets[j].Name);      end;      break;    end;  end;end;procedure TfrmNav.lbSheetsClick(Sender: TObject);var  wps, wb: Variant;  I, J: Integer;begin  if (lbExcels.ItemIndex = -1) or (lbSheets.ItemIndex = -1) then exit;  wps := GetOpenedExcel;  if varisempty(wps) then   begin    lbSheets.Clear;    exit;  end;  if wps.workbooks.count = 0 then  begin    lbSheets.Clear;    exit;  end;  for I := 1 to wps.workbooks.count do  begin    wb := wps.workbooks[I];    if wb.Name = lbExcels.Items[lbExcels.ItemIndex]	then    begin      wb.activate;      for j := 1 to wb.worksheets.count do      begin        if wb.worksheets[j].name = lbSheets.Items[lbSheets.ItemIndex] then        begin          wb.worksheets[j].activate;          break;        end;      end;      break;    end;  end;end;function TfrmNav.GetOpenedExcel: Variant;beginend;procedure TfrmNav.TestClick(Sender: TObject);var  wps, wb, sht: Variant;  I: Integer;begin  // Clear  lbExcels.Clear;  //  wps := GetOpenedExcel;  if VarIsEmpty(wps) or VarIsNull(wps) then    Exit;  if wps.Workbooks.Count = 0 then    Exit;  for I := 1 to wps.Workbooks.Count do    begin      wb := wps.Workbooks[I];      lbExcels.Items.Add(wb.Name);    end;end;end.