首页  编辑  

读取Excel 97 或2000工作表

Tags: /超级猛料/Office.OA自动化/Excel/   Date Created:
procedure TstartForm.SpeedButton10Click(Sender: TObject);
var
  MSExcel: Variant;
begin
  MSExcel := CreateOLEObject('Excel.Application');
  MSExcel.WorkBooks.Add;
  MSExcel.Visible := True;
  for i := 5 to Query1.RecordCount + 4 do
  begin
    MSExcel.Cells[i, 1].value := Query1.FieldByName('cpxhno').Asstring;
    MSExcel.Cells[i, 2].value := Query1.FieldByName('cpname').Asstring;
    MSExcel.Cells[i, 3].value := Query1.FieldByName('cpunit').Asstring;
    MSExcel.Cells[i, 4].value := Query1.FieldByName('htnumber').Asstring;
    MSExcel.Cells[i, 5].value := Query1.FieldByName('number').Asstring;
    MSExcel.Cells[i, 6].value := Query1.FieldByName('ljno').Asstring;
  end;
end;
退出Excel:
MSExcel.Quit;
MSExcel := Unassigned; // 释放VARIANT变
* * * * * * * * * * * * * * * 
先加入
ExcelApplication1;
ExcelWorkbook1;
ExcelWorksheet1;

procedure TForm1.n1Click(Sender: TObject);
var
  row, brea: integer;
  a, b, c, d, e: shortstring;
begin
  if table1.active = True then
  begin
    try
      ExcelApplication1.Connect;
    Except
      ExcelApplication1.free;
      Abort;
    end;
    brea := strtoint(inputbox('输入需导入行数!', '行数', '10'));
    if brea < 1 then
      brea := 10;
    ProgressBar1.Visible := True;
    ProgressBar1.Max := brea;
    ExcelApplication1.Visible[0] := True;
    for row := 2 to brea do
    begin
      a := ExcelWorksheet1.Cells.Item[row, 2];
      b := ExcelWorksheet1.Cells.Item[row, 1];
      c := ExcelWorksheet1.Cells.Item[row, 3];
      d := ExcelWorksheet1.Cells.Item[row, 4];
      e := ExcelWorksheet1.Cells.Item[row, 5];
      form1.show;
      table1.AppendRecord([a, b, c, d, e]);
      ProgressBar1.Position := row - 1;
    end;
    ProgressBar1.Hide;
  end;
end;
* * * * * * * * * * * * * * * * *

var
  MSExcel: Variant;
  i: integer;

begin
  OpenDialog1.Filter := '*.XLS|*.XLS';
  OpenDialog1.DefaultExt := 'XLS';
  if OpenDialog1.Execute then
  begin
    MSExcel := CreateOLEObject('Excel.Application');
    MSExcel.WorkBooks.Open(OpenDialog1.FileName);
    MSExcel.Visible := False;
    // 从有数据的行逐行读入数据
    for i := 1 to MSExcel.ActiveSheet.UsedRange.Rows.Count do
    begin
      Edit2.Text := Edit2.Text + MSExcel.Cells[i, 1].value;
    end;
    MSExcel.ActiveWorkBook.Close;
    MSExcel.Quit;
  end;
end;