用CLIENTDATASET保存查询结果,然后使用clientdataset.savetofile可以把其中的数据保存成.cds文件格式。
如果需要加密,可以通过使用文件流把.cds文件加上一些信息后在保存为其他格式的文件

解决方案 »

  1.   

    同意 cobi,   我以前也这么作的
      

  2.   

    ClientDataSet在Delphi 5及其更低的版本中有很严格的授权限制(只允许开发者使用,如果要用在用户的机子上还要交一大笔授权费)。虽然在国内不用很在意,但是对于大公司的话以后打起官司来问题会很多。
      

  3.   

    以下这个单元能把DBGrid里的一切输出成.Txt文件。
    unit DBExport;interfaceuses
      Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
      Db, DsgnIntf;resourcestring
      FILTER_TYPES   = 'Comma delimited file (*.csv)|*.csv|Text file (*.txt)|*.txt|Any file (*.*)|*.*';
      DEFAULT_FILTER = 'csv';type
      //===========================================================================
      // TDBExportOptions
      //===========================================================================
      TDBExportOption  = (eoAutoOpen, eoCanCancel, eoShowProgress);
      TDBExportOptions = set of TDBExportOption;
      TDBExportHeader  = (ehNone, ehFieldName, ehDisplayName);
    const
      DefaultOptions   = [eoAutoOpen, eoShowProgress];
    type
      //===========================================================================
      // TDBExport
      //===========================================================================
      TDBExport = class(TComponent)
      private // --------------------------------------------- Private declarations
        FDataSource     : TDataSource;
        FFieldDelimiter : Char;
        FFileName       : TFileName;
        FCaption        : TCaption;
        FHeader         : TDBExportHeader;
        FOptions        : TDBExportOptions;
        FOnExecute      : TNotifyEvent;
        FOnInitialize   : TNotifyEvent;
        FExecuting      : boolean;  protected // ----------------------------------------- Protected declarations
        procedure SetDataSource (Value : TDataSource);
        procedure Notification (AComponent : TComponent; Operation : TOperation); override;    function StoredCaption   : boolean;
        function GetFileName     : string;
        function GetHeader       : string;
        function GetRecord       : string;    function FilteredData (const Data : string) : string;
        function GetSeparator : Char;  public // ----------------------------------------------- Public declarations
        constructor Create (AOwner : TComponent); override;    function Execute        : boolean;
        property FieldDelimiter : Char             read FFieldDelimiter;  published // ----------------------------------------- Published declarations
        property DataSource     : TDataSource      read FDataSource     write SetDataSource;
        property FileName       : TFileName        read FFileName       write FFileName;
        property Caption        : TCaption         read FCaption        write FCaption stored StoredCaption;
        property Header         : TDBExportHeader  read FHeader         write FHeader  default ehNone;
        property Options        : TDBExportOptions read FOptions        write FOptions default DefaultOptions;    property OnExecute      : TNotifyEvent     read FOnExecute      write FOnExecute;
        property OnInitialize   : TNotifyEvent     read FOnInitialize   write FOnInitialize;
      end;  //===========================================================================
      // TDBExportEditor
      //===========================================================================
      TDBExportEditor = class (TComponentEditor)
        function GetVerbCount : integer;              override;
        function GetVerb (Index : integer) : string;  override;
        procedure ExecuteVerb (Index : integer);      override;
      end;  //===========================================================================
      // TDEFileNameProperty
      //===========================================================================
      TDEFileNameProperty = class(TStringProperty)
      public
        function GetAttributes : TPropertyAttributes; override;
        procedure Edit;                               override;
      end;procedure Register;implementation{$R *.DCR}uses FProgressAB;resourcestring
      DEF_CAPTION = 'Export data';//=============================================================================
    // PROTECTED METHODS
    //=============================================================================//-----------------------------------------------------------------------------
    // Procedure : SetDataSource
    //
    // Purpose   : SetDataSource.
    //-----------------------------------------------------------------------------
    procedure TDBExport.SetDataSource;
    begin
      if Value <> FDataSource then begin
        FDataSource := Value;
        if Assigned (FDataSource) then
          FDataSource.FreeNotification (Self);
      end;
    end;//-----------------------------------------------------------------------------
    // Function  : GetFileName
    //
    // Purpose   : GetFileName, display dialog if FileName is empty.
    // Output    : FileName.
    //-----------------------------------------------------------------------------
    function TDBExport.GetFileName;
    var
      FSaveDlg  : TSaveDialog;
    begin
      FSaveDlg  := TSaveDialog.Create (nil);
      try
        FSaveDlg.DefaultExt := DEFAULT_FILTER;
        FSaveDlg.FileName   := FFileName;
        FSaveDlg.Filter     := FILTER_TYPES;
        if FSaveDlg.Execute then
          Result := FSaveDlg.FileName
        else
          Abort;
      finally
        FSaveDlg.Free;
      end;
    end;//-----------------------------------------------------------------------------
    // Procedure : Notification
    //
    // Purpose   : Notification.
    //-----------------------------------------------------------------------------
    procedure TDBExport.Notification;
    begin
      inherited Notification (AComponent, Operation);
      if (Operation = opRemove) and (AComponent = FDataSource) then
        FDataSource := nil;
    end;//-----------------------------------------------------------------------------
    // Function  : FilteredData
    //
    // Purpose   : Quote data if it contains the delimiter.
    // Input     : string.
    // Output    : string.
    //-----------------------------------------------------------------------------
    function TDBExport.FilteredData;
    begin
      if Assigned (StrScan (PChar (Data), FFieldDelimiter)) then
        Result := AnsiQuotedStr (Data, '"')
      else
        Result := Data;
    end;//-----------------------------------------------------------------------------
    // Function  : GetHeader
    //
    // Purpose   : Get the Header.
    // Output    : string.
    //-----------------------------------------------------------------------------
    function TDBExport.GetHeader;
    var
      FieldIdx : integer;
    begin
      Result := '';
      with FDataSource.DataSet do
        for FieldIdx := 0 to FieldCount - 1 do
          if Fields[FieldIdx].Visible and not Fields[FieldIdx].IsBlob then
            case FHeader of
              ehFieldName   : Result := Result + Fields[FieldIdx].FieldName   + FFieldDelimiter;
              ehDisplayName : Result := Result + FilteredData (Fields[FieldIdx].DisplayName) + FFieldDelimiter;
            end;
      SetLength (Result, Length (Result) - 1);
    end;//-----------------------------------------------------------------------------
    // Function  : GetRecord
    //
    // Purpose   : Get the current record.
    // Output    : string.
    //-----------------------------------------------------------------------------
    function TDBExport.GetRecord;
    var
      FieldIdx : integer;
    begin
      Result := '';
      with FDataSource.DataSet do
        for FieldIdx := 0 to FieldCount - 1 do
          if Fields[FieldIdx].Visible and not Fields[FieldIdx].IsBlob then
            if (Fields[FieldIdx].DataType = ftString) then
              Result := Result + FilteredData (Fields[FieldIdx].AsString) + FFieldDelimiter
            else
              Result := Result + Fields[FieldIdx].AsString + FFieldDelimiter;
      SetLength (Result, Length (Result) - 1);
    end;//-----------------------------------------------------------------------------
    // Function  : StoredCaption
    //
    // Purpose   : Determine if Caption has to be Stored.
    //-----------------------------------------------------------------------------
    function TDBExport.StoredCaption;
    begin
      Result := FCaption <> DEF_CAPTION;
    end;//-----------------------------------------------------------------------------
    // Function  : GetSeparator
    //
    // Purpose   : Obtain List Separator from Windows.
    // Output    : Separator.
    //-----------------------------------------------------------------------------
    function TDBExport.GetSeparator;
    var
      Size : integer;
      Sep  : PChar;
    begin
      // Allocate seperator size.
      Size := GetLocaleInfo (LOCALE_USER_DEFAULT, LOCALE_SLIST, nil, 0);
      Sep  := StrAlloc (Size + 1);
      try
        GetLocaleInfo (LOCALE_USER_DEFAULT, LOCALE_SLIST, Sep, Size);
        Result := Sep^;
      finally
        StrDispose (Sep);
      end;
    end;//=============================================================================
    // PUBLIC METHODS
    //=============================================================================//-----------------------------------------------------------------------------
    // Function  : Execute
    //
    // Purpose   : Export data.
    //-----------------------------------------------------------------------------
    function TDBExport.Execute;
    var
      FContents : TStrings;
      FOpened   : boolean;
      Progress  : TProgressABForm;
    begin
      if FExecuting then Abort;
      Result     := False;
      Progress   := nil;
      FExecuting := True;
      try
        if Assigned (FOnExecute) then
          FOnExecute (Self);
        if Assigned (FDataSource) and Assigned (FDataSource.DataSet) then
        begin
          if Trim (FFileName) = '' then FFileName := GetFileName;
          if eoShowProgress in FOptions then Progress  := TProgressABForm.Create (nil);
          try
            if eoShowProgress in FOptions then begin
              Progress.StatusMessage := 'Initializing...';
              Progress.CanCancel     := eoCanCancel in FOptions;
              Progress.Caption       := FCaption;
              Progress.Show;
              Progress.Refresh;
            end;
            FDataSource.DataSet.DisableControls;
            if Assigned (FOnInitialize) then
              FOnInitialize (Self);
            try
              FOpened := (eoAutoOpen in FOptions) and (not FDataSource.DataSet.Active);
              FContents := TStringList.Create;
              try
                if FOpened then FDataSource.DataSet.Open;
                try
                  if (FHeader <> ehNone) then FContents.Add (GetHeader);
                  if (eoShowProgress in FOptions) then begin
                    Progress.MaxValue      := FDataSource.DataSet.RecordCount;
                    Progress.StatusMessage := 'Exporting...';
                  end;
                  FDataSource.DataSet.First;
                  while not FDataSource.DataSet.EOF do begin
                    FContents.Add (GetRecord);
                    FDataSource.DataSet.Next;
                    if eoShowProgress in FOptions then begin
                      Progress.ProgressBy (1);
                      if (eoCanCancel in FOptions) then Application.ProcessMessages;
                      if Progress.ModalResult <> mrNone then Abort;
                    end;
                  end;
                finally
                  if FOpened then FDataSource.DataSet.Close;
                end; // DataSet.Open
                if eoShowProgress in FOptions then Progress.StatusMessage := 'Saving...';
                FContents.SaveToFile (FFileName);
                Result := True;
              finally
                FContents.Free;
              end; // FContents.Create
            finally
              FDataSource.DataSet.EnableControls;
            end; // DataSet.DisableControls
          finally
            if eoShowProgress in FOptions then Progress.Release;
          end; // TProgressForm.Create
        end;
      finally
        FExecuting := False;
      end; // Executing
    end;//=============================================================================
    // CREATE/DESTROY METHODS
    //=============================================================================//-----------------------------------------------------------------------------
    // Constructor : Create
    //
    // Purpose     : Initialize instance.
    //-----------------------------------------------------------------------------
    constructor TDBExport.Create;
    begin
      inherited Create (AOwner);
      FFieldDelimiter := GetSeparator;
      FOptions        := DefaultOptions;
      FCaption        := DEF_CAPTION;
      FHeader         := ehNone;
    end;//=============================================================================
    // TDBExportEditor
    //=============================================================================//-----------------------------------------------------------------------------
    // Function  : GetVerbCount
    //-----------------------------------------------------------------------------
    function TDBExportEditor.GetVerbCount;
    begin
      Result := 1;
    end;//-----------------------------------------------------------------------------
    // Function  : GetVerb
    //-----------------------------------------------------------------------------
    function TDBExportEditor.GetVerb;
    begin
      case (index) of
        0 : Result := '&Export dataset';
      end; //case
    end;//-----------------------------------------------------------------------------
    // Procedure : ExecuteVerb
    //-----------------------------------------------------------------------------
    procedure TDBExportEditor.ExecuteVerb;
    begin
      case (index) of
        0 : (Component as TDBExport).Execute;
      end; //case
    end;//=============================================================================
    // TDEFilenameProperty
    //=============================================================================procedure TDEFilenameProperty.Edit;
    begin
      with (GetComponent(0) as TDBExport) do
      try
        FileName := GetFileName;
      except
        on EAbort do ;
      end;
    end;function TDEFilenameProperty.GetAttributes: TPropertyAttributes;
    begin
      Result := [paDialog, paRevertable];
    end;//=============================================================================
    // REGISTER
    //=============================================================================procedure Register;
    begin
      RegisterComponents('LeafControls', [TDBExport]);
      RegisterComponentEditor (TDBExport, TDBExportEditor);
      RegisterPropertyEditor (TypeInfo (string), TDBExport, 'FileName', TDEFilenameProperty);
    end;end.
      

  4.   

    Clus(叶不归),谢谢了.我试一下say的这个问题是帮我问的
    谢谢say 谢谢大家高手继续指点..
      

  5.   

    超苯,两个数据集,一个打开要复制的,
    一个打开要存储格式的xls,dbf文件等等,
    一个一个字段的Assign()也能转换过来。
    这么无聊的问题也能提出来?
      

  6.   

    to tjf1117(tjf1117)
       U! 来者不善呀!
       我太笨了,怎么看到你写“苯”呀!
       这里不欢迎说人家“苯”的家伙,沾污了这个学习的地方,请靠边!!!
      

  7.   

    但是tjf1117说的确实是比较通用的是据库之间方法,而且也比较可靠。就是写起来太麻烦了些。
      

  8.   

    我没说tjf1117的办法不行,只是他说话不要这么说,每个人总有问题的时候吧,他也不例外。到处说些风谅话来打击别人。好了这里是个学习、交流的地方不是吹牛的场所不想再说他了大家继续吧!
      

  9.   

    对!言论自由!!在此向tjf1117道歉啦!^-^不过大家也得办好事呀,帮帮忙呀!先谢过了!
      

  10.   

    在文档区里有使用Excel控件的方法,你可以将Dataset里的内容按照方法输出到Excel,然后提示用户使用Excel另存为其他格式就很方便了。