我想把dbgrid 中的数据导出为execl形式
要求 字段与execl的栅格相对应
可有源码,作为参考?
谢谢大侠

解决方案 »

  1.   

    Function DBGridToExcel(DBG:TDBGrid):boolean;                //DBGrid生成到Excel中.
    var
      tmpi,tmpj: integer;
      vExcel   : variant;
      vSheet1  : variant;
    begin
      result := false;
      try
        vExcel:=CreateOLEObject('Excel.Application');
      Except
        on E:Exception do begin
          showmessage('请检查机器是否已经安装MicroSoft Excel!');
          Exit;
        end;
      end;  vExcel.WorkBooks.Add;
      vExcel.WorkBooks[1].WorkSheets[1].Name:='Excel数据表1';
      vSheet1:=vExcel.WorkBooks[1].WorkSheets['Excel数据表1'];  tmpi := 1;
      for tmpj := 0 to DBG.Columns.Count-1 do
      begin
        vsheet1.cells.item[tmpi,tmpj+1] := DBG.Columns.Items[tmpj].Title.Caption;
      end;  dbg.DataSource.DataSet.First;
      while not dbg.DataSource.DataSet.Eof do
      begin
        inc(tmpi);
        for tmpj := 0 to DBG.Columns.Count-1 do
        begin
          vsheet1.cells.item[tmpi,tmpj+1] := DBG.Fields[tmpj].AsString;
        end;
        dbg.DataSource.DataSet.Next;
      end;  vExcel.Application.visible:=True;
      vExcel.Application.Quit;
      result := true;
    end;
      

  2.   

    procedure Tearningstool.Button1Click(Sender: TObject);
    var xlapp,xlbook,xlsheet:variant;
    i,j:integer;
    begin
    self.Cursor:=crHourGlass;
    xlapp:=createoleobject('excel.application');
    xlbook:=xlapp.workbooks.add;
    xlsheet:=xlbook.worksheets[1];
    xlsheet.cells[1,3]:=trim(edit17.Text)+'实发工资一览表';
    xlsheet.cells[2,1]:='帐号';
    xlsheet.cells[2,2]:='姓名';
    xlsheet.cells[2,3]:='金额';
    xlsheet.cells[2,4]:='';
    xlsheet.cells[2,5]:='帐号';
    xlsheet.cells[2,6]:='姓名';
    xlsheet.cells[2,7]:='金额';
    i:=3;
    for j:=1 to self.StringGrid2.rowcount-1 do
    begin
        xlsheet.cells[i,1]:=''''+trim(self.StringGrid2.Cells[0,j]);
        xlsheet.cells[i,2]:=trim(self.StringGrid2.Cells[1,j]);
        xlsheet.cells[i,3]:=trim(self.StringGrid2.Cells[2,j]);
        xlsheet.cells[i,4]:='';
        xlsheet.cells[i,5]:=''''+trim(self.StringGrid2.Cells[4,j]);
        xlsheet.cells[i,6]:=trim(self.StringGrid2.Cells[5,j]);
        xlsheet.cells[i,7]:=trim(self.StringGrid2.Cells[6,j]);
        i:=i+1;
    end;
    self.Cursor:=crDefault;
    xlapp.visible:=true;
    end;