我有一个查询模块,查询到的数据显示在:dbgrid中,想把dbgrid中的数据,导出(保存)到excel或者txt等文本中,该怎么实现??我用的是access库谢谢!!

解决方案 »

  1.   

    procedure ExpDataSetToExcel(Var TheDataSet:TDataSet);
    var
        s: TStringList;
        str: string;
        i: Integer;
        ASaveDialog: TSaveDialog;
        tofileName: string;
    begin
        str := '';
        tofileName := '';
        with TheDataSet do
        begin
           DisableControls;
           try
              for i := 0 to FieldCount - 1 do
                 str := str + fields[i].DisplayLabel + char(9);
              str := str + #13;
              if not IsEmpty then
              begin
                 First;
                 while not eof do
                 begin
                    for i := 0 to FieldCount - 1 do
                       str := str + Fields[i].AsString + char(9);
                    str := str + #13;
                    next;
                 end; //end while
              end;
           finally
              EnableControls;
           end;
        end;
        s := TStringList.Create;
        try
            s.Add(str);
            ASaveDialog := TSaveDialog.Create(nil);
            try
                ASaveDialog.Title := '保存文件';
                ASaveDialog.Filter := 'Microsof Excel (*.xls)|*.xls';
                if ASaveDialog.Execute then
                begin
                    tofileName := ASaveDialog.FileName;
                    if pos(uppercase('.xls'), uppercase(tofileName)) = 0 then
                        tofileName := tofileName + '.xls';
                    if Fileexists(tofileName) then
                    begin
                        if application.MessageBox('文件已存在,确认覆盖?', '提示', mb_okcancel + mb_defbutton1) = idok then
                        begin
                            Deletefile(pchar(tofileName));
                            s.SaveToFile(tofileName); //保存
                            application.MessageBox( '数据导出完毕!', '信息', MB_OK + MB_ICONINFORMATION);
                        end;
                    end
                    else
                    begin
                        s.SaveToFile(tofileName); //保存
                        application.MessageBox('数据导出完毕!', '信息', MB_OK + MB_ICONINFORMATION);
                    end;
                end;
            finally
                FreeAndNil(ASaveDialog);
            end;
        finally
            FreeAndNil(s);
        end;
    end;
    搜一下很多的!
      

  2.   

    比如按钮事件里
    ExpDataSetToExcel(DBGrid.DataSource.DataSet)