Title: TDBGrid Data To MS Word Table with AutoFormat Option
Question: How to export TDBGrid Data to Ms Word Table with different Formats.?
Answer:
1. Add the unit below (UGridToWord) to your working directory.
2. Add the unit name to your uses part.
3. call the procedure GridToword with its parameter
Grid : the grid you want to export
FormatNum: an integer between 0 and 42 as follows
0 = no format required
1..42 = your favorite format number ( I personally prefer 9)
Try it with different format numbers and watch Word do the job for you.
_____________________________________________________________________________
unit UGridToWord;
interface
uses SysUtils, StdCtrls,Classes, Graphics,
Db, Grids, DBGrids, ComObj;
procedure GridToWord (Grid :TDBGrid ; FormatNum :integer);
implementation
procedure GridToWord (Grid :TDBGrid ; FormatNum :integer);
var
x :integer ;
y: integer ;
Word : Olevariant ;
GColCount : integer ;
GRowCount : integer;
begin
Word := CreateOLEobject('Word.Application') ;
Word.Visible := True ;
Word.Documents.Add ;
GColCount := Grid.Columns.Count ;
GRowCount := Grid.DataSource.DataSet.RecordCount ;
Word.ActiveDocument.Range.Font.Size := Grid.Font.Size;
Word.ActiveDocument.PageSetup.Orientation := 1 ;
Word.ActiveDocument.Tables.Add( Word.ActiveDocument.Range,GRowCount+1,GColCount);
Word.ActiveDocument.Range.InsertAfter('Date ' + Datetimetostr(Now));
Word.ActiveDocument.Range.Tables.Item(1).AutoFormat(FormatNum,1,1,1,1,1,0,0,0,1);
for y := 1 to GColCount
do Word.ActiveDocument.Tables.Item(1).Cell(1,y).Range.InsertAfter(Grid.Columns[y-1].Title.Caption) ;
x :=1 ;
with Grid.DataSource.DataSet do begin
First ;
while not Eof do begin
x := x + 1 ;
for y := 1 to GColCount
do Word.ActiveDocument.Tables.Item(1).Cell(x,y).Range.InsertAfter(FieldByName(Grid.Columns[y-1].FieldName).Asstring);
Next ;
end;
end;
Word.ActiveDocument.Range.Tables.Item(1).UpdateAutoFormat ;
end;
end.