二、选择excel表'按钮,用于打开EXCEL文件,其代码如下:
procedure TForm1.Button1Click(Sender: TObject);
var i,j:integer;
begin
opendialog1.InitialDir:=ExtractFileDir(paramstr(0));//文件的打存放初始路径
opendialog1.Execute;
Try
ExcelApplication1.Connect;//EXCEL应用程序
Except
MessageDlg('Excel may not be installed',mtError, [mbOk], 0);
Abort;
End;
ExcelApplication1.Visible[0]:=True;
ExcelApplication1.Caption:='Excel Application';
try
excelapplication1.Workbooks.Open(opendialog1.FileName,
null,null,null,null,null,null,null,null,null,null,null,null,0);//打开指定的EXCEL 文件
except
begin
ExcelApplication1.Disconnect;//出现异常情况时关闭
ExcelApplication1.Quit;showmessage('请选择EXCEL电子表格!');
exit;
end;
end;
ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks[1]);//ExcelWorkbook1与Eexcelapplication1建立连接
ExcelWorksheet1.ConnectTo(ExcelWorkbook1.Worksheets[1] as _Worksheet);//Excelworksheet1与Excelworkbook1建立连接
//开始从EXCEL中取数,放到stringgrid1中,取完数后关闭EXCEL
for i:=1 to 1000 do//最大取值1000
for j:=1 to 6 do
begin
if trim(excelworksheet1.cells.item[i+1,1])<>'' then
begin
stringgrid1.rowCount:=i+1;
stringgrid1.Cells[j,i]:=ExcelWorksheet1.Cells.Item[i+1,j];
end
else
begin
label3.caption:=inttostr(i-1);
ExcelApplication1.Disconnect;
ExcelApplication1.Quit;
//将第一条数据赋给编辑框
edit2.text:=stringgrid1.Cells[1,1];
edit1.text:=stringgrid1.Cells[2,1];
edit3.text:=stringgrid1.Cells[3,1];
edit4.text:=stringgrid1.Cells[4,1];
edit5.text:=stringgrid1.Cells[5,1];
exit;
end;
end;
end;
三、'下一条记录'按钮,完成记录向下移动,代码如下:
procedure TForm1.Button2Click(Sender: TObject);
var x:integer;
begin
x:=stringgrid1.row+1;
if x<> stringgrid1.RowCount then
begin
stringgrid1.row:=stringgrid1.row+1;
label1.caption:=inttostr(x);
edit2.text:=stringgrid1.Cells[1,x];
edit1.text:=stringgrid1.Cells[2,x];
edit3.text:=stringgrid1.Cells[3,x];
edit4.text:=stringgrid1.Cells[4,x];
edit5.text:=stringgrid1.Cells[5,x];
exit;
end
else
showmessage('已到第一条记录!');
end;
四、'上一条记录',完成记录上移,代码如下:
var x:integer;
begin
x:=stringgrid1.row-1;
if x<>0 then
begin
stringgrid1.row:=stringgrid1.row-1;
label1.caption:=inttostr(x);
edit2.text:=stringgrid1.Cells[1,x];
edit1.text:=stringgrid1.Cells[2,x];
edit3.text:=stringgrid1.Cells[3,x];
edit4.text:=stringgrid1.Cells[4,x];
edit5.text:=stringgrid1.Cells[5,x];
exit;
end
else
showmessage('已到最后一条记录!');
end;
五、stringgrid中上下移动时代码:
procedure TForm1.StringGrid1Click(Sender: TObject);
var i:integer;
begin
i:=stringgrid1.Row;
label1.caption:=inttostr(i);
edit1.text:=stringgrid1.Cells[2,i];
edit2.text:=stringgrid1.Cells[1,i];
edit3.text:=stringgrid1.Cells[3,i];
edit4.text:=stringgrid1.Cells[4,i];
edit5.text:=stringgrid1.Cells[5,i];
end;