Use the CreateoleObject method in Delphi to operate the Word file

xiaoxiao2021-03-06  21

Using the CreateoleObject method, the CreateoleObject method is "closer" from the Word core operation than the control methods provided by Delphi, because it uses the VBA language provided by Office. The operation of the Word document is programmed.

The following is the experiment I did on this machine, the machine software configuration is as follows:

Windows XP Delphi7.0 Office 2003

This program is very simple, placing an Edit and a button on the page, each click a button, will automatically add the contents of the EDIT in the Word document in the background, the program is shut down, the file is automatically saved in the current program. Directory.

Unit main;

Interface

// If you want to use CreateoleObject to operate on the Word document, you should add Comobj statements in the Uses // statement and WordXP Declaration Uses Windows, Messages, Sysutils, Variants, Classes, Graphics, Controls, Forms, ComoBJ, WordXP, Dialogs, STDCTRLS;

type TForm1 = class (TForm) Button1: TButton; Edit1: TEdit; procedure Button1Click (Sender: TObject); procedure FormCreate (Sender: TObject); procedure FormClose (Sender: TObject; var Action: TCloseAction); // procedure Button2Click (Sender : TOBJECT); private {private declarations}

Var Form1: TForm1; // State the two variables as global variables fword: variant; fdoc: variant;

IMPLEMentation

{$ R * .dfm}

Procedure tForm1.Button1Click (Sender: TOBJECT); beginfword.seection.typeParagraph; fword.selection.Typetext (text: = form1.edit1.text);

Procedure TFORM1.FormCreate (Sender: TOBJECT); Begin // Create an object, if an exception occurs, make a prompt tryfword: = createoleObject ('word.application'); // Word program execution is visible, the value is FALSE In the background, fword.visible: = false; ExceptShowMessage ('Create a Word object failed!'); Exit;

// Create a new page in the open word, then type "Hello," Enter "World!" Tryfdoc: = fword.Sselection.Typetext (Text: = 'Hello , '); Fword.seection.typeParagraph; fword.selection.typetext (text: =' world! ');

EXCEPTON E: Exception DoshowMessage (E.MESSAGE); END; END;

// Save the contents in the current directory while the program is closed, and close the Word program procedure tform1.formclose (Sender: Tobject; VAR Action: TcloseAction); beginfdoc.saveas (ExtractFilepath); beginfdoc.saves; Exename) 'Test.doc'; fword.quit; fword: = unassigned; end; end.

In addition, the operation of other documents of Office is similar, not described. This method can also complete more complex documentation by reference to a more complex VBA macro in the Word file.

转载请注明原文地址:https://www.9cbs.com/read-39642.html

New Post(0)