狼行神码

导航

打开电子表格

界面如图所示:

代码如下:

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids,comobj;// comobj
 8 
 9 type
10   TForm1 = class(TForm)
11     OpenDialog1: TOpenDialog;
12     StringGrid1: TStringGrid;
13     Button1: TButton;
14     procedure Button1Click(Sender: TObject);
15   private
16     { Private declarations }
17   public
18     { Public declarations }
19   end;
20 
21 var
22   Form1: TForm1;
23 var
24   excelapp,Sheet:Variant;      //声明excel变量
25   MaxRow, MaxCol,X, Y:integer ;
26   str:string;
27 implementation
28 
29 {$R *.dfm}
30 
31 procedure TForm1.Button1Click(Sender: TObject);
32 begin
33   if opendialog1.Execute then
34   begin
35   Str:=trim(form1.OpenDialog1.FileName); //Trim 函数作用是去掉字符串中多加上去的空格
36   excelapp := CreateOleObject('excel.application');  //创建 Excel 对象
37   excelapp.Workbooks.open(Str);    //打开已存在的工作簿 ExcelApp.WorkBooks.Open ( '' C : \Excel\Demo.xls '' ) ;
38   Sheet := excelapp.WorkSheets[1];  //工作表1复制给sheet
39 
40   MaxRow := Sheet.Usedrange.EntireRow.count ;    //工作表行
41   MaxCol := sheet.Usedrange.EntireColumn.count;  //工作表列
42 
43   form1.StringGrid1.RowCount:=maxRow+1;     //工作表行数给StringGrid1
44   form1.StringGrid1.ColCount:=maxCol+1;     //工作表列数给StringGrid1
45   for x:=1 to maxCol do                     //工作表内容赋值StringGrid1
46     for y:=1 to maxRow do
47       form1.stringgrid1.Cells[x,y]:=sheet.cells.item[y,x].value;
48   excelapp.Workbooks.close;
49   end;
50 end;
51 
52 end.

 

posted on 2017-05-25 12:55  狼行神码  阅读(219)  评论(0编辑  收藏  举报