Delphi操作Excel(1) ---获取excel的行数和列数

来源:互联网 发布:seo sem 新媒体工资 编辑:程序博客网 时间:2024/05/17 03:17

说明:

      程序中使用OLE来操作EXCEL。需要在uses中写上ComObj.

 

使用属性来获取行数和列数:

     使用代码1提供的代码获取的excel中的行数和列数,不包括开头的空行和空列。

 

1   TemperMaxRows   := ExcelApp.worksheets[1].Usedrange.Rows.count;   {代码1}
2   TemperMaxcolumns:= ExcelApp.worksheets[1].Usedrange.columns.count;

包含开头空行和空列的行数和列数:

    如果想获得最大行数(列数),需要在程序中去判断。

判断方法:

    1、先假设TemperMaxRows为最大行,然后去判断每一列的元素是否都为非空,如果有一列全部为空,则列数加1,最终得到实际的最大列数

    2、根据计算到的实际最大列数,然后去判断每一行的元素是否都为非空,如果有一行全部为空,则行数加1,最终得到实际的最大行数。

代码示例:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->  1 unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, Grids, Menus,ComObj;type  TForm1 = class(TForm)    strngrd1: TStringGrid;    mm1: TMainMenu;    File1: TMenuItem;    Open1: TMenuItem;    dlgOpen1: TOpenDialog;    ExcelFile1: TMenuItem;    Open2: TMenuItem;    procedure Open2Click(Sender: TObject);    procedure FormClose(Sender: TObject; var Action: TCloseAction);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;  ExcelApp : Variant;  FileDirectory:string;implementation{$R *.dfm}procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);begin  ExcelApp.WorkBooks.Close;  ExcelApp.quit;end;procedure TForm1.Open2Click(Sender: TObject);var  i,j:Integer;  tempermaxRow,maxRow:Integer;  tempermaxcolumn,maxcolumn : Integer;  flag:Boolean;begin  dlgOpen1.Execute;  FileDirectory := dlgOpen1.FileName; {获取文件的路径名}  Text := FileDirectory;  ExcelApp := CreateOleObject( 'Excel.Application' );{ ExcelApp.Visible := True;}  ExcelApp.workbooks.Open('E:\我的文档\Delphi程序\Delphi操作excel\book1.xls');  for I := 01 to 20 do {读取excel中的数据}    strngrd1.Cells[1,i] := ExcelApp.cells[i,2];  {excel单元格不是从[0,0]开始的}  {获取数据中的使用的行数和列数,如果开头的行(列)内容全为空,则不计算到总数内。}   tempermaxRow :=  ExcelApp.worksheets[1].Usedrange.Rows.count;   tempermaxcolumn := ExcelApp.worksheets[1].Usedrange.columns.count;     ShowMessage(Format('程序中获取的行数:%d,程序中获取的列数%d',[tempermaxRow,tempermaxcolumn]));     Maxcolumn := tempermaxcolumn;     maxRow := tempermaxRow;     flag := false;  for i  := 1 to tempermaxcolumn  do    begin      for j := 1 to maxRow do        begin          if ExcelApp.cells[j,i].value <> '' then          begin            flag := True;            Continue;          end;        end;      if (flag = False) then        Maxcolumn := Maxcolumn + 1;    end;  flag := false;  for i  := 1 to tempermaxRow  do    begin      for j := 1 to maxcolumn  do        begin          if ExcelApp.cells[i,j].value <> '' then          begin            flag := True;            Continue;          end;        end;      if (flag = False) then        maxRow := maxRow + 1;    end;{将空行也计算到总数内}  ShowMessage(Format('实际行数:%d,实际列数%d',[maxRow,Maxcolumn]));end;end.


0 0
原创粉丝点击