我在delphi中用控件dbgrid显示了数据库中的一个表,现在要导出去,导出格式为html 和excel,怎么写代码啊??还有,我想打印此表,又怎么写啊???求求大家指点一下了,有点急啊!!!!!!!!小弟万分感谢!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!小弟的分已经不多了,不能给大家更多分的了

解决方案 »

  1.   

    这个有一些复杂,不是一两句可以说清楚的。可以从网上搜索一下,看看有没有比较经典的代码!Excel可能要简单一些,可以将Excel作为Ado连接的一个数据库,让后向EXCEL里面插入数据,HTML可能就比较复杂一些了,如果没有控件的话,就需要自己手工写代码创建一个HTML文件。这些链接可以参考一下:
    http://www.was.gov.cn/snb/snbblog/blogview.asp?logID=30
    http://ykaiyan.blogchina.com/3338784.html
    http://csdn.aehk.com/4534.htmhttp://www.baidu.com/s?ie=gb2312&bs=DataGrid+%B5%BC%B3%F6+Excel&sr=&z=&cl=3&f=8&wd=dbGrid+%B5%BC%B3%F6+Excel&ct=0
      

  2.   

    我在delphi中用控件dbgrid显示了数据库中的一个表,现在要导出去,导出格式为html 和excel,怎么写代码啊??
    ---------------------------------------------------------------------------------
    导出为html,你把dbgrid的烈数和行数得到后,自己往一个文本文件中写标记就可以了,最后保存为htm格式。导出到excel,提供代码如下:
    procedure CopyDbDataToExcel(Args: array of const);
    var
      iCount, jCount: Integer;
      XLApp: Variant;
      Sheet: Variant;
      I: Integer;
    begin
      Screen.Cursor := crHourGlass;
      if not VarIsEmpty(XLApp) then
      begin
        XLApp.DisplayAlerts := False;
        XLApp.Quit;
        VarClear(XLApp);
      end;  try
        XLApp := CreateOleObject(‘Excel.Application‘);
      except
        Screen.Cursor := crDefault;
        Exit;
      end;  XLApp.WorkBooks.Add;
      XLApp.SheetsInNewWorkbook := High(Args) + 1;  for I := Low(Args) to High(Args) do
      begin
        XLApp.WorkBooks[1].WorkSheets[I+1].Name := TDBGrid(Args[I].VObject).Name;
        Sheet := XLApp.Workbooks[1].WorkSheets[TDBGrid(Args[I].VObject).Name];    if not TDBGrid(Args[I].VObject).DataSource.DataSet.Active then
        begin
          Screen.Cursor := crDefault;
          Exit;
        end;    TDBGrid(Args[I].VObject).DataSource.DataSet.first;
        for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do
          Sheet.Cells[1, iCount + 1] :=
        TDBGrid(Args[I].VObject).Columns.Items[iCount].Title.Caption;    jCount := 1;
        while not TDBGrid(Args[I].VObject).DataSource.DataSet.Eof do
        begin
          for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do
            Sheet.Cells[jCount + 1, iCount + 1] :=
          TDBGrid(Args[I].VObject).Columns.Items[iCount].Field.AsString;      Inc(jCount);
          TDBGrid(Args[I].VObject).DataSource.DataSet.Next;
        end;
        XlApp.Visible := True;
      end;
      Screen.Cursor := crDefault;
    end; 打印 TDBGrid内容
    procedure PrintDbGrid(DataSet:TDataSet;DbGrid:TDbGrid;Title:String);
    var
    PointX,PointY:integer;
     ScreenX:integer;
     i,lx,ly:integer;
     px1,py1,px2,py2:integer;
     RowPerPage,RowPrinted:integer;
     ScaleX:Real;
     THeight:integer;
     TitleWidth:integer;
     SumWidth:integer;
     PageCount:integer;
     SpaceX,SpaceY:integer;
     RowCount:integer;
    begin
    PointX:=Round(GetDeviceCaps(printer.Handle,LOGPIXELSX)/2.54);
    PointY:=Round(GetDeviceCaps(printer.Handle,LOGPIXELSY)/2.54);
     ScreenX:=Round(Screen.PixelsPerInch/2.54);
    ScaleX:=PointX/ScreenX;
     RowPrinted:=0;
     SumWidth:=0;
     printer.BeginDoc;
     With Printer.Canvas do
     begin
      DataSet.DisableControls;
       DataSet.First ;
       THeight:=Round(TextHeight('我')*1.5);//设定每行高度为字符高的1.5倍
       SpaceY:= Round(TextHeight('我')/4);
       SpaceX:=Round(TextWidth('我')/4);
       RowPerpage:=Round((printer.PageHeight-5*PointY)/THeight); //上下边缘各2厘米
       ly:=2*PointY;
       PageCount:=0;
      while not DataSet.Eof do
       begin
        if (RowPrinted=RowPerPage) or (RowPrinted=0) then
         begin
          if RowPrinted<>0 then
          Printer.NewPage;
           RowPrinted:=0;
           PageCount:=PageCount+1;
           Font.Name:='宋体';
           Font.size:=16;
           Font.Style:=Font.Style+[fsBold];
           lx:=Round((Printer.PageWidth-TextWidth(Title))/2);
           ly:=2*PointY;
           TextOut(lx,ly,Title);
           Font.Size:=11;
           Font.Style:=Font.Style-[fsBold];
           lx:=Printer.PageWidth-5*PointX;
           ly:=Round(2*PointY+0.2*PointY);
           if RowPerPage*PageCount>DataSet.RecordCount then
            RowCount:=DataSet.RecordCount
           else
           RowCount:=RowPerPage*PageCount;
           TextOut(lx,ly,'第'+IntToStr(RowPerPage*(PageCount-1)+1)+'-'+IntToStr(RowCount)+'条,共'+IntToStr(DataSet.RecordCount)+'条');
           lx:=2*PointX;
           ly:=ly+THeight*2;
           py1:=ly-SpaceY;
           if RowCount=DataSet.RecordCount then
            py2:=py1+THeight*(RowCount-RowPerPage*(PageCount-1)+1)
           else
            py2:=py1+THeight*(RowPerPage+1);
           SumWidth:=lx;
           for i:=0 to DBGrid.Columns.Count-1 do
           begin
           px1:=SumWidth-SpaceX;
             px2:=SumWidth;
             MoveTo(px1,py1);
             LineTo(px2,py2);
             TitleWidth:=TextWidth(DBGrid.Columns[i].Title.Caption);
             lx:=Round(SumWidth+(DBGrid.Columns[i].width*scaleX-titleWidth)/2);
             TextOut(lx,ly,DBGrid.Columns[i].Title.Caption);
             SumWidth:=Round(SumWidth+DBGrid.Columns[i].width*scaleX)+SpaceX*2;
           end;
           px1:=SumWidth;      //画最后一条竖线
           px2:=SumWidth;
           MoveTo(px1,py1);
           LineTo(px2,py2);
           px1:=2*PointX;            //画第一条横线
         px2:=SumWidth;
          py1:=ly-SpaceY;
          py2:=ly-SpaceY;
           MoveTo(px1,py1);
           LineTo(px2,py2);
           py1:=py1+THeight;
           py2:=py2+THeight;
           MoveTo(px1,py1);
           LineTo(px2,py2);
         end;
       lx:=2*PointX;
         ly:=ly+THeight;
         px1:=lx;
         px2:=SumWidth;
         py1:=ly-SpaceY+THeight;
         py2:=ly-SpaceY+THeight;
         MoveTo(px1,py1);
         LineTo(px2,py2);
         for i:=0 to DBGrid.Columns.Count-1 do
         begin
           TextOut(lx,ly,DataSet.FieldByname(DBGrid.Columns[i].Fieldname).AsString);
           lx:=Round(lx+DBGrid.Columns[i].width*ScaleX+SpaceX*2);
         end;
         RowPrinted:=RowPrinted+1;
         DataSet.next;
       end;
       DataSet.first;
       DataSet.EnableControls;
     end;
     printer.EndDoc;
    end;
      

  3.   

    既然代码很复杂,那么你去下载TMS组件,里面有个advStringGrid,导出 Excel只需要几行代码,那个可能更适合你,www.delphifans.com
      

  4.   

    提供给您一个组件,组件代码是:
    unit PrintSQL_Data;
    interface
    uses
      SysUtils, Classes,Messages, Variants, Graphics, Controls, Forms,
      Dialogs,windows,ADODB,ComObj,Excel2000,RzPrgres;type
      TPrintSQL_Data = class(TComponent)
      private
        { Private declarations }
        FDataSet:TADODataSet;
        FActive:Boolean;
        FSQLString:string;
        FExcelTitle:TCaption;
        FPrinting:Boolean;
        FExcelFileName:string;
        procedure SetSQLString(Value:string);
        procedure SetExcelTitle(Value:TCaption);
        procedure SetExcelFileName(Value:string);
        procedure SetActive(Value:Boolean);
        procedure SetPrinting(Value:Boolean);
        procedure SetDataSet(Value:TADODataSet);
        //打印
        Function GetExcelCoulmnCaption(num:Cardinal):string;
      protected
        { Protected declarations }
      public
        { Public declarations }
        Constructor Create(AOwner:TComponent); Override;
        Destructor Destroy; override;
        procedure PrintSqlDataToExcel; overload;
        procedure PrintSqlDataToExcel(PB:TRzProgressBar); overload;
      published
        { Published declarations }
        property SQLString:string
                 read FSQLString
                 write SetSQLString;    property DataSet:TADODataSet
                 read FDataSet
                 write SetDataSet;    property ExcelTitle:TCaption
                 read FExcelTitle
                 write SetExcelTitle;
        property ExcelFileName:String
                 read FExcelFileName
                 write SetExcelFileName;    property Active:boolean
                 read FActive
                 write SetActive;
        property Printing:boolean
                 read FPrinting
                 write SetPrinting;  end;procedure Register;implementationprocedure Register;
    begin
      RegisterComponents('rocxu', [TPrintSQL_Data]);
    end;{ TPrintSQL_Data }constructor TPrintSQL_Data.Create(AOwner: TComponent);
    begin
      inherited Create(AOwner);
    end;destructor TPrintSQL_Data.Destroy;
    begin
      inherited;
    end;function TPrintSQL_Data.GetExcelCoulmnCaption(num: Cardinal): string;
    var
      mod_num,div_num:Cardinal;
    begin
       if num=0 then exit;
       if (num mod 26=0) then mod_num:=26
       else mod_num:=num mod 26;
       div_num:=num div 26;
       if mod_num=26 then DEC(div_num);
       if div_num=0 then
       Result:=Chr(64+mod_num)
       else Result:=Chr(64+div_num)+Chr(64+mod_num);
    end;procedure TPrintSQL_Data.PrintSqlDataToExcel;
    var
      I:integer;
      Range,ExcelApp,V:variant;
    begin
        Try
          ExcelApp:=CreateOleObject('Excel.application');
        Except
          MessageDlg('没有安装Office 办公软件Excel!',mtinformation,[MBOK],0);
          exit;
        End;    try
        ExcelApp.WorkBooks.add(Null);
        V:=ExcelApp.WorkBooks[1].WorkSheets[1];    //*开始设计标题*/
        Range:=V.Range['A1',GetExcelCoulmnCaption(DataSet.Fields.Count)+'1'];
        Range.MergeCells:=true;
        Range.RowHeight:=24;
        Range.HoriZontalAlignMent:=xlCenter;
        Range.VerticalAlignMent:=xlCenter;
        Range.Font.Name:='新宋体';
        Range.Font.size:=16;
        Range.Font.FontStyle:='加粗';
        Range.Value:=FExcelTitle;
        Range.Borders.LineStyle:=xlContinuous;  //边框
        Range.Borders.Weight:=xlThin;
        Range.Borders.ColorIndex:=xlAutomatic;    //显示标题
         For i:=0 To DataSet.Fields.Count-1 Do
         begin
           Range:=V.Range[GetExcelCoulmnCaption(I+1)+'2',GetExcelCoulmnCaption(I+1)+'2'];
           Range.RowHeight:=24;
           Range.HoriZontalAlignMent:=xlCenter;
           Range.VerticalAlignMent:=xlCenter;
           Range.Font.Name:='新宋体';
           Range.Font.size:=9;
           Range.Font.FontStyle:='加粗';
           Range.Columns.AutoFit;
           Range.Value:=DataSet.Fields[I].FieldName;
           Range.Borders.LineStyle:=xlContinuous;  //边框
           Range.Borders.Weight:=xlThin;
           Range.Borders.ColorIndex:=xlAutomatic;
         end;
         //显示内容
         //set
          Range:=V.Range['A3',GetExcelCoulmnCaption(DataSet.FieldCount)+IntToStr(DataSet.recordcount+2)];
          Range.NumberFormatLocal:= '@';
          Range.RowHeight:=20;
          Range.HoriZontalAlignMent:=xlCenter;
          Range.VerticalAlignMent:=xlCenter;
          Range.Borders.LineStyle:=xlContinuous;  //边框
          Range.Borders.Weight:=xlThin;
          Range.Borders.ColorIndex:=xlAutomatic;
          Range.Font.Name:='新宋体';
          Range.Font.size:=9;
          Range.Columns.AutoFit;     DataSet.First;
         While (Not DataSet.Eof) do
         begin
            For i:=0 To DataSet.Fields.Count-1 Do
            begin
                 Range:=V.Range[GetExcelCoulmnCaption(I+1)+IntToStr(DataSet.RecNo+2),GetExcelCoulmnCaption(I+1)+IntToStr(DataSet.RecNo+2)];
                 if  DataSet.Fields[I].IsNull then
                 Range.Value:=' '
                 else
                 Range.Value:=DataSet.Fields[I].AsString;
                 Range.Borders.LineStyle:=xlContinuous;  //边框
                 Range.Borders.Weight:=xlThin;
                 Range.Borders.ColorIndex:=xlAutomatic;
            end;
            DataSet.next;
         end;
         
        //显示Excel文档界面
        ExcelApp.visible:=true;
        V.Activate;
        finally
           //释放接口对象
            ExcelApp:=unassigned;
            V:= unassigned;
            Range:=unassigned;
        end;
    end;
      

  5.   

    procedure TPrintSQL_Data.PrintSqlDataToExcel(PB: TRzProgressBar);
    var
      I:integer;
      Range,ExcelApp,V:variant;
    begin
        Try
          ExcelApp:=CreateOleObject('Excel.application');
          PB.PartsComplete:=0;
        Except
          MessageDlg('没有安装Office 办公软件Excel!',mtinformation,[MBOK],0);
          exit;
        End;    try
        ExcelApp.WorkBooks.add(Null);
        V:=ExcelApp.WorkBooks[1].WorkSheets[1];    //*开始设计标题*/
        Range:=V.Range['A1',GetExcelCoulmnCaption(DataSet.Fields.Count)+'1'];
        Range.MergeCells:=true;
        Range.RowHeight:=24;
        Range.HoriZontalAlignMent:=xlCenter;
        Range.VerticalAlignMent:=xlCenter;
        Range.Font.Name:='新宋体';
        Range.Font.size:=16;
        Range.Font.FontStyle:='加粗';
        Range.Value:=FExcelTitle;
        Range.Borders.LineStyle:=xlContinuous;  //边框
        Range.Borders.Weight:=xlThin;
        Range.Borders.ColorIndex:=xlAutomatic;    //显示标题
         For i:=0 To DataSet.Fields.Count-1 Do
         begin
           Range:=V.Range[GetExcelCoulmnCaption(I+1)+'2',GetExcelCoulmnCaption(I+1)+'2'];
           Range.RowHeight:=24;
           Range.HoriZontalAlignMent:=xlCenter;
           Range.VerticalAlignMent:=xlCenter;
           Range.Font.Name:='新宋体';
           Range.Font.size:=9;
           Range.Font.FontStyle:='加粗';
           Range.Columns.AutoFit;
           Range.Value:=DataSet.Fields[I].FieldName;
           Range.Borders.LineStyle:=xlContinuous;  //边框
           Range.Borders.Weight:=xlThin;
           Range.Borders.ColorIndex:=xlAutomatic;
         end;
         //显示内容
         //set
          Range:=V.Range['A3',GetExcelCoulmnCaption(DataSet.FieldCount)+IntToStr(DataSet.recordcount+2)];
          Range.NumberFormatLocal:= '@';
          Range.RowHeight:=20;
          Range.HoriZontalAlignMent:=xlCenter;
          Range.VerticalAlignMent:=xlCenter;
          Range.Borders.LineStyle:=xlContinuous;  //边框
          Range.Borders.Weight:=xlThin;
          Range.Borders.ColorIndex:=xlAutomatic;
          Range.Font.Name:='新宋体';
          Range.Font.size:=9;
          Range.Columns.AutoFit;     PB.TotalParts:=DataSet.RecordCount;
         DataSet.First;
         While (Not DataSet.Eof) do
         begin
            For i:=0 To DataSet.Fields.Count-1 Do
            begin
                 Range:=V.Range[GetExcelCoulmnCaption(I+1)+IntToStr(DataSet.RecNo+2),GetExcelCoulmnCaption(I+1)+IntToStr(DataSet.RecNo+2)];
                 if  DataSet.Fields[I].IsNull then
                 Range.Value:=' '
                 else
                 Range.Value:=DataSet.Fields[I].AsString;
                 Range.Borders.LineStyle:=xlContinuous;  //边框
                 Range.Borders.Weight:=xlThin;
                 Range.Borders.ColorIndex:=xlAutomatic;
            end;
            PB.IncPartsByOne;
            DataSet.next;
         end;    //显示Excel文档界面
        ExcelApp.visible:=true;
        V.Activate;
        finally
           //释放接口对象
            ExcelApp:=unassigned;
            V:= unassigned;
            Range:=unassigned;
            PB.PartsComplete:=0;
        end;
    end;procedure TPrintSQL_Data.SetActive(Value: Boolean);
    begin
       If Value then
       begin
         If DataSet.Connection<>nil then
         begin
             try
               With DataSet do
               begin
                 IF Active then Active:=false;
                 Commandtext:=FSQLString;
                 Active:=true;
                 FActive:=Value;
               end;
             except
                on E:Exception do
                MessageDlg('查询操作失败!'+#13#10+'异常类:'+E.ClassName+#13#10+'错误信息代码为:'+E.Message,mtinformation,[MBOK],0);
             end;
         end
         else MessageDlg('没有选择数据库连接对象!',mtinformation,[MBOK],0);
        end else begin
                    FActive:=Value;
                    Fprinting:=False;
                 end;
    end;procedure TPrintSQL_Data.SetDataSet(Value: TADODataSet);
    begin
      FDataSet:=Value;
    end;procedure TPrintSQL_Data.SetExcelFileName(Value: string);
    begin
       FExcelFileName:=Value;
    end;
    procedure TPrintSQL_Data.SetExcelTitle(Value: TCaption);
    begin
       FExcelTitle:=value;
    end;procedure TPrintSQL_Data.SetPrinting(Value: boolean);
    begin
        if Active then
        begin
         if self.DataSet.Fields.Count>0 then
          if Value then
          PrintSqlDataToExcel;
        end else FPrinting := Value;
    end;procedure TPrintSQL_Data.SetSQLString(Value: string);
    begin
       FSQLString:=Value;
       FActive:=false;
       FPrinting:=False;
    end;
    end.
      

  6.   

    procedure CopyDbDataToExcel(Args: array of const); 这句是什么意思啊??CopyDbDataToExcel它是什么控件啊??我想知道就一个简单的例子:我在form1中添加ADOConnection1,adoquery1,DataSource1,dbgrid四个控件.两个按扭分别是"显示表"和"导出excel",请问还需要什么啊??在哪里添加呢??我总觉得procedure CopyDbDataToExcel(Args: array of const);中的代码不知道往哪里面加哦???????