Open and edit a Word template from Delphi

I need to be able to open and edit a Word template from Delphi (using Word). I can open the OK template, but Word assumes that this is a document, not a template.

The problem is that I need to edit the template and not use it as a template for a new document. I use templates as part of a workflow system, and I want users to be able to edit templates from my application. As of now, they should open Word, and then open the template from there and edit it - making it from my application will be easier and safer.

Experimental code

fWordApp: WordApplication; TempName: OleVariant; WordDoc: WordDocument; TemplateFile: string; begin TemplateFile := Settings.Directories.RootInsert(qryTemplates.FieldByName('fldtemplate_path').AsString); if TemplateFile <> '' then begin if not Assigned(fWordApp) then begin fWordApp := CreateOleObject('Word.Application') as WordApplication; while fWordApp.Templates.Count = 0 do Sleep(200); // Normal.dot must be loaded end; if Assigned(fWordApp) then fWordApp.Visible := True else raise Exception.Create('Cannot initialize Word application'); TempName := TemplateFile; WordDoc := fWordApp.Documents.Add(TempName, EmptyParam, wdFormatTemplate, EmptyParam); 
+4
source share
2 answers

As I understand it, you are using the wrong method. The Add method is used to create a new document. You can pass the name of the template file so that the new document is based on this template.

But you want to open an existing document and edit it. It does not matter that the document is a template. You still need to open it. And for this you need the Open method. Here's a pretty trivial example.

 var WordApp, Doc: Variant; begin WordApp := CreateOleObject('Word.Application'); WordApp.Visible := True; Doc := WordApp.Documents.Open('path\to\my\template.dotx'); Doc.Range.Text := 'Merry Christmas everyone'; Doc.Save; WordApp.Quit; end; 

I used late binding because I found it easier for this example. But you must stick to your early approach. You will have to navigate that the open method accepts many parameters. I think you can just pass EmptyParam everyone except the first parameter.

+7
source

There are thousands of Delphi functions for working with Word: http://delphimagic.blogspot.com.es/2013/03/funciones-para-trabajar-con-word.html

+2
source

All Articles