Activex OLE Delphi

Title: Exporting Grid to MS Word without using OLE&Components
Question: How to save objects to Word compatible format
Answer:
For exporting grid you may create Word compatible file in RTF format.This is a simple example of saving string grid named StringGrid1 to file grid.rtf:
procedure WriteToStream(var Stream:TStream; s:string);
begin
Stream.Write(PChar(s)^,Length(s));
end;
procedure TForm1.ReportBtnClick(Sender: TObject);
var St:TStream; f,r,cellwidth,cellpos:integer;
begin
St:=TFileStream.Create('grid.rtf',fmCreate);
try
//RTF header
WriteToStream(St,'{\rtf1\ansi\deff0\deflang1033');
WriteToStream(St,'{\fonttbl{\f0\fnil\fcharset1{\*\fname Arial;}Arial;}}');
WriteToStream(St,'\viewscale100\uc1\pard\f0\fs20\par');
cellwidth:=2988;
//Writing Grid Data
for r:=0 to StringGrid1.RowCount-1
do begin
WriteToStream(St,'{\trowd\trgaph70\trleft0\trrh230');
cellpos:=cellwidth;
for f:=0 to StringGrid1.ColCount-1 do begin
WriteToStream(St,'\clvertalt\clbrdrt\brdrs\brdrw10');
WriteToStream(St,'\clbrdrl\brdrs\brdrw10');
WriteToStream(St,'\clbrdrb\brdrs\brdrw10');
WriteToStream(St,'\clbrdrr\brdrs\brdrw10');
WriteToStream(St,'\cellx'+inttostr(cellpos));
cellpos:=cellpos+cellwidth;
end;
for f:=0 to StringGrid1.ColCount-1 do begin
WriteToStream(St,'\pard\plain\fs20\intbl ' + text2rtf(StringGrid1.Cells[f,r])+'\cell ');
end;
WriteToStream(St,'\row }');
end;//for r
//End of RTF file
WriteToStream(St,'\par }');
finally
if Assigned(St) then St.Free;
end;
showmessage('Export complete. Results are in file grid.rtf');
end;
This is function text2rtf used in procedure above:
function text2rtf(s:string):string;
const s2:string=''; i:integer=1;
begin
while ido begin
case ord(s[i]) of
92: s2:=s2+'\\';
123: s2:=s2+'\{';
125: s2:=s2+'\}';
128..255: s2:=s2+'\'''+inttohex(ord(s[i]),2);
else s2:=s2+s[i];
end;//case
inc(i);
end;
Result:=s2;
end;
This procedure creates Word compatible file without using OLE.
However, if you want to get a native Word document you may save a copy of file,
using OleVariant Word object:
procedure TForm1.DocBtnClick(Sender: TObject);
var V:OleVariant;
begin
try
V:=CreateOLEObject('Word.Application');
V.Documents.Open('grid.rtf');
V.ActiveDocument.SaveAs('grid.doc',0,False, '', True,'',False,False,False, False,False);
V.Quit(0);
V:=UnAssigned;
showmessage('Save complete');
except
showmessage('Could not save file document as doc');
end;
end;
See also my another article How to make reports in RTF format