type
  TForm1 = class(TForm)
    ADOQuery1: TADOQuery;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    FExcelBook: TExcelWorkBook;
    FExcelSheet: TExcelWorkSheet;
    FExcelApp: TExcelApplication;
    procedure DataSetToExcel(AFileName: string);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    { Public declarations }
  end;var
  Form1: TForm1;implementation{$R *.dfm}procedure TForm1.DataSetToExcel(AFileName: string);
begin
  try
    FExcelApp.Visible[0] := False;
    try
      FExcelBook.ConnectTo(FExcelApp.Workbooks.Add(EmptyParam, 0));
    except
      raise Exception.Create('连接到Excel文件出错,可能是没有安装Excel软件');
    end;                
    FExcelSheet.ConnectTo(FExcelBook.Worksheets[1] as _WorkSheet);
    with FExcelSheet.QueryTables.Add(ADOQuery1.Recordset, FExcelSheet.Range['A3', EmptyParam], EmptyParam) do
    begin
      FieldNames := False;
      Refresh(False);
    end;  
    FExcelSheet.Columns.Item[3, EmptyParam].NumberFormatLocal := 'yyyy-mm-dd';
    FExcelBook.SaveCopyAs(AFileName);
    FExcelBook.Close(False);
  finally
    FExcelApp.Quit;
    FExcelSheet.Disconnect;
    FExcelBook.Disconnect;
    FExcelApp.Disconnect;
  end;
end;{ TForm1 }constructor TForm1.Create(AOwner: TComponent);
begin
  inherited;
  FExcelApp := TExcelApplication.Create(Self);
  FExcelBook := TExcelWorkBook.Create(Self);
  FExcelSheet := TExcelWorkSheet.Create(Self);
end;destructor TForm1.Destroy;
begin
  FExcelSheet.Free;
  FExcelBook.Free;
  FExcelApp.Free;
  inherited;
end;procedure TForm1.Button1Click(Sender: TObject);
begin
  Caption := 'begin open';
  with ADOQuery1 do
  begin  
    if not Active then 
    begin
      SQL.Text := 'select * from  mytable';
      Open;
    end;
    DataSetToExcel('c:\a.xls');
  end;
end;这是利用Excel内置的功能,其它的功能各位再试试了。还有一篇是直接写Excel文件格式的:
http://www.delphibbs.com/delphibbs/dispq.asp?lid=1051160试过,两万的记录当然是写XLS格式快点,快他只是给出写一个Sheet的,而上面内置的,可以有多个Sheet,不过没有进度而已。自己选择了。

解决方案 »

  1.   

    改了一下:
    unit ExportExcel;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls, ADODB, DB, Excel2000;type
      TStatus = (stInitExcel, stOpenDataSet, stExportData, stSetFont, stSaveFile, stError);
      TExportStatus = procedure(Index: Integer; Status: TStatus) of object;
      TInitExcelBook = procedure(ExcelBook: TExcelWorkBook) of object;
      TExportSheet = function(const Index: Integer;
        out ASQLText: string; out AFieldName: Boolean;
        out AFontName: string; out AFontSize: Integer): Boolean of object;  TForm1 = class(TForm)
        Button1: TButton;
        Memo1: TMemo;
        procedure Button1Click(Sender: TObject);
      private
        FThread: TThread;
        procedure OnStatus(Index: Integer; Status: TStatus);
        procedure InitExcelBook(ExcelBook: TExcelWorkBook);
        function ExportSheet(const Index: Integer;
          out ASQLText: string; out AFieldName: Boolean;
          out AFontName: string; out AFontSize: Integer): Boolean;
      end;var
      Form1: TForm1;implementationuses ActiveX;
    {$R *.dfm}type
      TDataSetToExcel = class(TThread)
      private
        FFileName: string;
        FDataSet: TADOQuery;
        FExcelBook: TExcelWorkBook;
        FExcelSheet: TExcelWorkSheet;
        FExcelApp: TExcelApplication;
        FOnExportSheet: TExportSheet;
        FOnInitExcelBook: TInitExcelBook;
        FOnStatus: TExportStatus;
        procedure DoStatus(Index: Integer; Status: TStatus);
        function GetAfterOpen: TDataSetNotifyEvent;
        procedure SetAfterOpen(Value: TDataSetNotifyEvent);
        function DoExportSheet(const Index: Integer;
          out ASQLText: string; out AFieldName: Boolean;
          out AFontName: string; out AFontSize: Integer): Boolean;
      protected
        procedure Execute; override;
      public
        constructor Create(AFileName: string; AADOConnString: string = '');
        destructor Destroy; override;
        property OnStatus: TExportStatus read FOnStatus write FOnStatus;
        property OnExportSheet: TExportSheet read FOnExportSheet write FOnExportSheet;
        property OnInitExcelBook: TInitExcelBook read FOnInitExcelBook write FOnInitExcelBook;
        property OnDataSetAfterOpen: TDataSetNotifyEvent read GetAfterOpen write SetAfterOpen;
      end;{ TDataSetToExcel }constructor TDataSetToExcel.Create;
    begin
      FFileName := AFileName;
      FDataSet := TADOQuery.Create(nil);
      FDataSet.ConnectionString := AADOConnString;
      FExcelBook := TExcelWorkBook.Create(nil);
      FExcelSheet := TExcelWorkSheet.Create(nil);
      FExcelApp := TExcelApplication.Create(nil);
      FreeOnTerminate := True;
      inherited Create(True);
    end;destructor TDataSetToExcel.Destroy;
    begin
      FDataSet.Free;
      FExcelBook.Free;
      FExcelSheet.Free;
      FExcelApp.Free;
      inherited Destroy;
    end;function TDataSetToExcel.DoExportSheet(const Index: Integer;
      out ASQLText: string; out AFieldName: Boolean;
      out AFontName: string; out AFontSize: Integer): Boolean;
    begin
      Result := False;
      if Assigned(FOnExportSheet) then
        Result := FOnExportSheet(Index, ASQLText, AFieldName, AFontName, AFontSize);
    end;procedure TDataSetToExcel.DoStatus(Index: Integer; Status: TStatus);
    begin
      if Assigned(FOnStatus) then FOnStatus(Index, Status);
    end;procedure TDataSetToExcel.Execute;
    var
      FieldName: Boolean;
      SQLText, FontName: string;
      FontSize, Index, RowCount, ColCount: Integer;
    begin
      CoInitialize(nil);
      try
        try
          FExcelApp.Visible[0] := False;
          try
            DoStatus(-1, stInitExcel);
            FExcelBook.ConnectTo(FExcelApp.Workbooks.Add(EmptyParam, 0));
            if Assigned(FOnInitExcelBook) then
              FOnInitExcelBook(FExcelBook);
          except
            raise Exception.Create('连接到Excel文件出错,可能是没有安装Excel软件');
          end;      try
            Index := 1;
            while DoExportSheet(Index, SQLText, FieldName, FontName, FontSize) do
            begin
              DoStatus(Index, stOpenDataSet);
              with FDataSet do
              begin
                if Active then Close;
                SQL.Text := SQLText;
                try
                  Open; First;
                  ColCount := FieldCount;
                  RowCount := RecordCount;
                except
                  raise Exception.Create('SQL语句出错.');
                end;
              end;          DoStatus(Index, stExportData);
              FExcelSheet.ConnectTo(FExcelBook.Worksheets[Index] as _WorkSheet);
              with FExcelSheet.QueryTables.Add(FDataSet.Recordset,
                FExcelSheet.Range['A2', EmptyParam], EmptyParam) do
              begin
                FieldNames := FieldName;
                Refresh(False);
              end;          DoStatus(Index, stSetFont);
              with FExcelSheet do
              begin
                with Range[Cells.Item[1, 1], Cells.Item[RowCount + 1, ColCount]] do
                begin
                  Font.Name := FontName;
                  Font.Size := FontSize;
                end;
                with Range[Cells.Item[1, 1], Cells.Item[RowCount + 1, ColCount]] do
                  Borders.LineStyle := xlContinuous;
              end;
              Inc(Index);
            end;        DoStatus(-1, stSaveFile);
            FExcelBook.SaveCopyAs(FFileName);
            FExcelBook.Close(False);
          finally
            FExcelApp.Quit;
            FExcelSheet.Disconnect;
            FExcelBook.Disconnect;
            FExcelApp.Disconnect;
          end;
        except
          DoStatus(-1, stError);
        end;
      finally
        CoUnInitialize;
      end;
    end;function TDataSetToExcel.GetAfterOpen: TDataSetNotifyEvent;
    begin
      Result := FDataSet.AfterOpen;
    end;procedure TDataSetToExcel.SetAfterOpen(Value: TDataSetNotifyEvent);
    begin
      FDataSet.AfterOpen := Value;
    end;const
      Conn =
        'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=dbname;Data Source=servername';{ TForm1 }//这里进行SQL语句,之类的设置。
    function TForm1.ExportSheet(const Index: Integer; out ASQLText: string;
      out AFieldName: Boolean; out AFontName: string;
      out AFontSize: Integer): Boolean;
    begin
      Result := Index <= 5;
      ASQLText := 'select * from ValueDictionary';
      AFieldName := False;
      AFontName := '宋体';
      AFontSize := 9;
    end;// 初始化你的ExcelWorkBook
    procedure TForm1.InitExcelBook(ExcelBook: TExcelWorkBook);
    var
      Index: Integer;
      Sheet: _WorkSheet;
    begin
      Index := ExcelBook.Worksheets.Count;
      while Index < 5 do
      begin
        Sheet := ExcelBook.Worksheets.Add(EmptyParam, EmptyParam,
          EmptyParam, EmptyParam, 0) as _WorkSheet;
        Inc(Index);
      end;
      for Index := 1 to 5 do
        (ExcelBook.Sheets.Item[Index] as _WorkSheet).Name := IntToStr(Index);
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      Thread: TDataSetToExcel;
    begin
      Thread := TDataSetToExcel.Create('c:\a.xls', Conn);
      Thread.OnStatus := OnStatus;
      Thread.OnExportSheet := ExportSheet;
      Thread.OnInitExcelBook := InitExcelBook;
      FThread := Thread;
      FThread.Resume;
    end;// 工作状态
    procedure TForm1.OnStatus(Index: Integer; Status: TStatus);
    const
      S: array [TStatus] of string = ('stInitExcel', 'stOpenDataSet',
         'stExportData', 'stSetFont', 'stSaveFile', 'stError');
    var
      E: Exception;
    begin
      Memo1.Lines.Add(Format('Index: %d, Status: %s', [Index, S[Status]]));
      case Status of
        stSaveFile:
          FThread := nil;
        stError:
        begin
          E := Exception(ExceptObject);
          Memo1.Lines.Add(Format('Error: %s', [E.Message]));
        end;
      end;
    end;end.
      

  2.   

    c:\>....哼哼...
    c:\>....唧唧...
      

  3.   

    to copy_paste:
       还没有开学里.
       你在上班吗?
       偷空来灌水,不怕被老板罚啊?
      

  4.   

    再说一句,最好,将Form的内容也贴一下就更好了.
      

  5.   

    朋友,我是初学者,搞不太懂也,能否把form文件的内容贴出来,我仔细研究研究!!!
      

  6.   


    不会吧,这是DataToExcel单元的Form,随便copy这些代码,玩玩看就是了。object Form1: TForm1
      Left = 192
      Top = 107
      Width = 544
      Height = 375
      Caption = 'Form1'
      Color = clBtnFace
      Font.Charset = DEFAULT_CHARSET
      Font.Color = clWindowText
      Font.Height = -11
      Font.Name = 'MS Sans Serif'
      Font.Style = []
      OldCreateOrder = False
      PixelsPerInch = 96
      TextHeight = 13
      object Button1: TButton
        Left = 56
        Top = 72
        Width = 75
        Height = 25
        Caption = 'Button1'
        TabOrder = 0
        OnClick = Button1Click
      end
      object Memo1: TMemo
        Left = 184
        Top = 24
        Width = 337
        Height = 313
        Lines.Strings = (
          'Memo1')
        TabOrder = 1
      end
    end
      

  7.   

    天下真是好人多!
    借着这个问题,我查了过去的贴子,发现关于导出至excel文件的方法有很多,我也跟着学习了一下。结果,我发现有一个方法自认识是最简单的:先安装好ehlib控件,然后再uses DBGridEhif savedialog1.Execute then
    SaveDBGridEhToExportFile(TDBGridEhExportAsxls, DBGridEh1, SaveDialog1.FileName, True);即可输出xls文件。
      

  8.   

    导出EXCEL文件其实很多,很多情况下可以选择导出成CVS格式的,或文本格式的,EXCEL就直接能够查看。但这只是单个SHEET的情况下。很多时候是需要导出多个DataSet到一个XLS文件中,并对应各个不同的Sheet,所以这个就有用武之处了。而且,是尽可能的不要使用第三方组件。
      

  9.   

    而且导出的CVS或文本时如果太大,那么用EXCEL打开时,它需要读取到自己认识的格式,这个速度会随着那文件的大小而变慢。
      

  10.   

    这种办法其实很慢的。最快的方法是直接写Excel文件。—————————————————————————————————
    宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
    —————————————————————————————————
      

  11.   

    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  |我要到BCB去灌水    |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  |我要到BCB去灌水    |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  |我要到BCB去灌水    |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  | 我要到BCB去灌水   |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  |我要到BCB去灌水    |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  | 我要到BCB去灌水   |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  |我要到BCB去灌水    |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  | 我要到BCB去灌水   |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  |我要到BCB去灌水    |  |
              ︶                     ︶
    /               \           /              \
    |                \         /                |
    |            ︵   \       /   ︵            |
    \︶\︶\︶|︶|  \   \     /   /  |︶|︶/︶/︶/
     \  \  \ |  |    ︶       ︶    |  | /  /  /
      ︶ ︶╰|  |                   |  |╯︶ ︶
             |︶|                   |︶|
             |  | 我要到BCB去灌水   |  |
              ︶                     ︶