var
  I,J : integer;
  TxtFile : TextFile;
  TmpString : String;
begin
  try
    if VarIsEmpty(XlsApp) then
      XlsApp := CreateOleObject('Excel.Application');
    XlsSheet := XlsApp.workbooks.open('c:\my documents\book3.xls');
    AssignFile(TxtFile,'C:\My Documents\Test.txt');
    Rewrite(TxtFile);
    try
      for I := 3 to 21 do
      begin
        TmpString := '';
        for J := 1 to 5 do
        begin
          TmpString := TmpString + XlsSheet.ActiveSheet.Cells[I,J].Text + '|';
        end;
        Writeln(TxtFile,Tmpstring);
      end;
    finally
      CloseFile(TxtFile);
    end;
    XlsApp.Visible := true;
  except
    XlsSheet.close;
    XlsApp.Application.quit;
    XlsApp := Unassigned;
    XlsSheet := Unassigned;
  end;
end;

解决方案 »

  1.   

    在uses中加入ComObj,如:uses windows,comobj……
    然后看下面一段:(例子而已)
    procedure TFwxrbb.BprintClick(Sender: TObject);
    var
      ExcelID:Variant;
      row:integer;
      fromfile, tofile: file;
      numread,numwritten:integer;
      buf: Array [0..2048] of Char;
    begin
      with wwTdayreport do
      begin
        first;
        if not EOF then
        begin
          //以下为复制一excel文件
          AssignFile(tofile,'rbb.xls');
          ReWrite(tofile,1);
          AssignFile(fromfile,'wxrbb.xls');
          ReSet(fromfile,1);
          numread:=2048;
          repeat
            BlockRead(fromfile,buf,sizeof(buf),numread);
            BlockWrite(tofile,buf,numread,numwritten);
          until (NumRead = 0) or (NumWritten <> NumRead);
          CloseFile(tofile);
          CloseFile(fromfile);
          //以下为创建文件应用
          ExcelID:=CreateOleObject('Excel.Application');
          ExcelID.Visible:=False; //是否可看见excel的应用窗口
          ExcelID.WorkBooks.Open('E:\Delphi\rbb.xls');
          row:=6;
        end;
        while not EOF do
        begin
          if row<>6 then
            ExcelID.ActiveSheet.Rows[row].Insert;//插入一行
          ExcelID.Cells[row,1].Value:=FieldByName('ManGroup').AsString;//填写单元格
          ExcelID.Cells[row,2].Value:=FieldByName('PayMethod').AsString;
          ExcelID.Cells[row,3].Value:=FieldByName('CustomerName').AsString;
          ExcelID.Cells[row,4].Value:=FieldByName('CustomerCar').AsString;
          ExcelID.Cells[row,5].Value:=FieldByName('CarName').AsString;
          ExcelID.Cells[row,6].Value:=FieldByName('Price').AsString;
          next;
          row:=row+1;
        end;
        ExcelID.ActiveWorkBook.Saved:=True;//不出现保存提示
        ExcelID.ActiveWorkBook.Save;//保存
        ExcelID.WorkBooks.Close;
        ExcelID.Quit;
      end;
    end;
    其它:
    指定边框宽度:ExcelID.ActiveSheet.Range[A1:F8].Borders[2].Weight:=4;
    设置字体:ExcelID.ActiveSheet.rows[1].Font.Name:='宋体'
    把上句Name改为Color为颜色,Bold为黑体等