请提供一种在DELPHI中做导入导出程序的好的方法.谢谢

解决方案 »

  1.   

    procedure TfrmSearch.bbtnExportClick(Sender: TObject);
    var
      xlsFilename :string;
      ExcelApp,WorkBook : variant ;
      FieldCount : Integer;
      i,j : Integer;
    begin
      bbtnExport.Enabled := False;
      FieldCount := dgridSearchList.Columns.Count;
      try
        ExcelApp := CreateOleObject('Excel.Application');
        WorkBook :=CreateOleObject('Excel.Sheet');
      except
        Application.MessageBox('您的系统没有安装MicroSoft EXCEL软件,数据不能导出!','错误提示',MB_OK+MB_SystemModal+MB_IconStop);
        bbtnExport.Enabled := True;
        exit;
      end;  if SaveDialog.Execute then
      begin
        xlsFilename := SaveDialog.FileName;
        if  FileExists(xlsFilename) then
        begin
          if Application.MessageBox('该文件已经存在,是否覆盖?','确认',MB_ICONQUESTION+MB_YESNO)=IDYES then
            DeleteFile(xlsFilename)
          else
          begin
            bbtnExport.Enabled := True;
            exit;
          end;
        end;
      end
      else
      begin
        bbtnExport.Enabled := True;
        exit;
      end;  try
        try
          WorkBook :=ExcelApp.WorkBooks.Add ;
          for i:=1 to  FieldCount do      //转化字段名;
            ExcelApp.Cells.Item(1,i) := dgridSearchList.Columns[i-1].Title.Caption ;      qrySearch.First;
          for i:=1 to qrySearch.RecordCount do
          begin
            for j:=1 to  FieldCount do  //转化一个记录
              begin
                ExcelApp.Cells.Item(i+1,j) :=dgridSearchList.Fields[j-1].AsString ;
              end;
            qrySearch.Next ;
          end;      try
            WorkBook.saveas(xlsFilename);
            Application.MessageBox('保存完毕!','提示',MB_OK+MB_SystemModal+MB_IconInformation);
          except
            Application.MessageBox('保存文件出现异常!','错误提示',MB_OK+MB_SystemModal+MB_IconStop);
          end;
        except
          Application.MessageBox('不能正确操作EXECL文件,可能该文件已经被其他程序占用或系统错误!','错误提示',MB_OK+MB_SystemModal+MB_IconStop);
        end;
      finally
        WorkBook.close;
        ExcelApp.quit;
        ExcelApp := Unassigned;
        bbtnExport.Enabled := True;
      end;
    end;