首页  编辑  

导出DBGrid到Word

Tags: /超级猛料/Office.OA自动化/Word/   Date Created:

导出DBGrid为Word表格。

procedure TForm1 . Button1Click ( Sender : TObject );

var

 WordApp , WordDoc , WordTable : OleVariant ;

 i , j : integer ;

begin

 WordApp := CreateOleObject ( 'Word.Application' );

 WordApp . Visible := True ;

 WordDoc := WordApp . Documents . Add ;

 WordTable := WordDoc . Tables . Add ( WordApp . Selection . Range , DBGrid1 . DataSource . DataSet . RecordCount + 1 , DBGrid1 . Columns . Count );

  for i := 1 to DBGrid1 . Columns . Count do

 WordTable . Cell ( 1 , i ). Range . InsertAfter ( DBGrid1 . Columns [ i - 1 ]. Title . Caption );

 i := 2 ;

  with DBGrid1 . DataSource . DataSet do

  while not eof do

  begin

    for j := 1 to DBGrid1 . Columns . Count do

     WordTable . Cell ( i , j ). Range . InsertAfter ( DBGrid1 . Columns [ j - 1 ]. Field . Value );

   Next ;

   Inc ( i );

  end ;

end ;