Delphi operation Word

Calling Word in Delphi    
    
uses ComObj ;

procedure TForm1.Button1Click(Sender: TObject);

var

vWord,vDoc,vRange : Variant ;

sText,sReplace : string ;

lReturn : Boolean ;

begin sText

:= 'ABCDEFG' ; //Original text string

sReplace := 'GFEDCBA' ; //New string

vWord := CreateOleObject('Word.Application') ;//Create Word thread

try

//Open the file to be operated

vDoc := vWord.Documents.Open('C:Documents. Doc');

vDoc.Select ; //Select the entire document

vRange := vDoc.Range ; //Replace the range

lReturn := True ;

while lReturn do

begin //Return True if found and replaced successfully, a total of 11 parameters

lReturn := vDoc.Range.Find.Execute(sText,,,,,,,,,sReplace,True) ;

end ;

finally

vDoc.Close(True) ; //Close the text and save

vWord.Quit(False) ; //Quit Word

end ;

end;

 

 

The process of calling Word is as above, printing
vDoc.PrintOut

Look carefully above

 

 

 

Delphi operation word
1. The Delphi program starts Word
using the CreateOleObjects method to start Word, and calls the VBA code. The specific implementation process is as follows:
First, use GetActiveOleObject('Word.Application') to determine whether there is a Word program in the current memory, if so,
directly Connect, if there is no Word program, use CreateOleObject('Word.Application') to start Word

2. New Word document format in Delphi program : WordDocuments.Add(Template,NewTemplate,DocumentType,Visible) Template: Use the name of the template, NewTemplate: The type of the new document, True means the template, False means the document DocumentType: The document type, the default Visible for a blank document : Whether the salvaged window is visible




举例:Doc_Handle:=Word_Ole.Documents.Add(Template:='C:\Temlate.dot',NewTemplate:=False);

3. Delphi program to open Word document
format: WordDocuments.Open(FileName, ConfirmConversions, ReadOnly, PassWordDocument,
PasswordTemplate, Revent, WritePasswordDocument, WritePassWordTemplate,
Format, Encoding, Visible)

FileName: Document name (including path)
Confirmconversions: Whether to display the file conversion dialog
ReadOnly: Whether to open the document as read-only
AddToRecentFiles: Whether to add the file to the recent files list at the bottom of the File menu PassWordDocument: Whether to open this document Password Required PasswordTemplate: Password required to open this template Revert: Whether to reopen the document if it has already been written WritePasswordDocument: Save the password required to save changes to the document WritePasswordTemplate: Save the password required to save changes to the template Format: Open the document The file converter you need to use when Encoding: The document code page used Visible: Whether the window to open the document is visible







举例:
Doc_Handle:=Word_Ole.Documents.open(FileName:=Doc_File,ReadOnly:=False,
AddToRecentFiles:=False);

Fourth, the Delphi program saves the Word document
format: WordDocuments.SaveAs(FileName, FileFormat, LockComments, Password,
AddToRecentFiles, WritePassword, ReadOnlyRecommended,
EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData,
SaveAsAOCELetter)

FileName: The file name. Defaults to the current folder and file name.
FileFormat The format in which the document is saved.
LockComments If  True, only comments are allowed for this document.
Password The password to open the document.
AddToRecentFiles If True, adds documents to the list of recently used documents in the File menu. WritePassword The password required to save modifications to the document. ReadOnlyRecommended If  True, Word will recommend read-only to the user each time the document is opened. EmbedTrueTypeFonts If  True, saves the document with  TrueType fonts. SaveNativePictureFormat If  True, graphics imported from other system platforms (eg  Macintosh) are only saved with their  Windows version. SaveFormsData If  True, save the data entered by the user in the form as a data record. SaveAsAOCELetter If the document contains an attachment, when this property is  True, saves the document as an  AOCE letterhead (and saves the mail).





举例:
Word_Ole.Documents.SaveAs(FileName:=Doc_File,FileFormat=wdFormatDocument,
AddToRecentFiles=False);

Five, read files from the database to the local hard disk and read files from the local hard disk to the database

Use the Image binary field to save on the database , and use the Stream stream method.

创建文件流:
Word_FileStream:=TFileStream.Create(Target_Name,fmOpenWrite or fmCreate);
Word_FileStream.Position:=0;

Image field saved to database : TBlobField(AdoQuery1.FieldByName(Column_Name)).SaveToStream(Word_FileStream);

Read file from database to local hard disk:
TBlobField(ADOQuery1.FieldByName(Column_Name)).loadfromStream(Word_FileStream);

Free the file stream:
Word_FileStream.Free;

Sixth, the definition of global message
Because word and Delphi programs are two softwares, it is more troublesome to communicate with each other, so the method of global message is used.
The global message must be registered first, and Windows returns the idle message number of the system. When the registered messages are the same, the
Windows system returns the same value, which ensures that the message number is used to communicate between the two programs.

The way to define the message:
szMessageString: pchar = 'XIDIAN_11_Stone';
FMyJoinMessage := RegisterWindowMessage(szMessageString);

The method of sending a message:
SendMessage (the counterparty handle, message, message with short variable, message with long variable )

Seven, Delphi program to receive
messages There are two ways for Delphi to receive messages, one is to overload a specific message, the other is to overload the WndProc function, and select the corresponding message for processing.
Method 1 can only process one message at a time, while method 2 can process multiple messages at the same time.

For method 2, the declaration is as follows:
procedure WndProc(var Message: TMessage);override
It must be noted that when using it, you need to inherit the WndProc(Message) function after processing your own message , otherwise the system will crash!

Eight, the dynamic generation of the Combo dialog box in Word and the Change event to create a class module Combohander, internally define the event Public WithEvents ComboBoxEvent As Office.CommandBarComboBox

Define the module
Dim ctlComboBoxHandler As New ComboBoxHandler that generates events for the Combo control

Generate a Combo dialog
Set Cbo_ChooseDoc = CommandBars("Added menu ").Controls.Add(Type:=msoControlComboBox, Temporary:=True)

Set the file handle to generate the Combo_Change event
Set ctlComboBoxHandler.ComboBoxEvent = Cbo_ChooseDoc

After the event is generated, select the Change event of ComboBoxEvent in the class module Combohander to write the event code Sub ComboBoxEvent_Change(ByVal Ctrl As Office.CommandBarComboBox)

 

// look carefully at the following method


The Word events handled in the VBA code are: Document_Close The Application events that need to be handled are: DocumentBeforeClose, DocumentChange.

Document_Close: The event generates an event when the document is closed.
DocumentBeforeClose: Before the document is closed, it is judged whether the document is saved before Word, and the corresponding prompt is given and processed accordingly.
DocumentChange: Document switching, which generates events when the document is switched between the document modified by itself and the document modified by others,
mainly dealing with setting document permissions, etc.

A set of Servers components are provided in Dephi 5 to achieve seamless integration with Office

  1. Create a Word file named after the title field in the current program directory

  exepath:=application.ExeName;

  for index:=1 to length(exepath) do

  if exepath[index]='\' then

  i:=index;

  exepath:=copy(exepath,1,i);

  doc_file:=exepath+mc+'.doc';

Name the Word file  with the title field "mc"

  try

  Wordapplication1.connect;

  except

  messagedlg(' Word is not installed',mterror,[mbok],0);

  abort;

  end;

  Wordapplication1.Caption := 'XX Plan ';

  Wordapplication1.visible := true;

  Worddocument1.activate;

  2. Set the paper size

  Wordapplication1.ActiveDocument.PageSetup.PageWidth:=XXX;

  Wordapplication1.ActiveDocument.PageSetup.PageHeight:=XXX;

  Wordapplication1.ActiveDocument.PageSetup.LeftMargin := XX;

  //set the left margin

  Wordapplication1.ActiveDocument.PageSetup.rightMargin := XX; 

  //set the right margin

  3. Insert page numbers

  var fpage, pagea: olevariant;

  fpage:=true;

  page: = wdAlignPageNumberCenter;

  Wordapplication1.activedocument.sections.item(1).Footers.item(1).PageNumbers.Add(pagea,fpage);

  4. Set the page to print horizontally

  s:=Wordapplication1.selection.start;

  e:=Wordapplication1.selection.start;

  aa:=wdSectionBreakNextPage;

  Wordapplication1.ActiveDocument.Range(s,e).InsertBreak(aa);

  Wordapplication1.Selection.Start:=Wordapplication1.Selection.Start + 1;

  s:=Wordapplication1.Selection.start;

  e:=Wordapplication1.ActiveDocument.Content.End_;

  Wordapplication1.ActiveDocument.Range(S,e).PageSetup.Orientation:=wdOrientLandscape;

  5. Set the font and font size

  Wordapplication1.Selection.Font.Size:=18;

  Wordapplication1.Selection.Font.Name := 'bold ';

  Wordapplication1.Selection.TypeParagraph;

  Wordapplication1.Selection.ParagraphFormat.Alignment:= wdAlignParagraphCenter;

  Wordapplication1.Selection.TypeParagraph;

  Wordapplication1.Selection.TypeText(dbedit4.text);

  //title 

  Wordapplication1.Selection.Font.Size := 14;

  Wordapplication1.Selection.Font.Name := 'Song ';

  Wordapplication1.Selection.TypeParagraph;

  Wordapplication1.Selection.TypeParagraph;

  Wordapplication1.Selection.ParagraphFormat.Alignment := wdAlignParagraphJustify;

  Wordapplication1.Selection.TypeText(' '+trim(dbmemo1.text));

  //text

   ... ...

  6. Insert form

  Wordapplication1.Selection.Font.Size :=10;

  adoquery2.Active:=false;

  adoquery2.active:=true;

  doc:=Wordapplication1.activedocument;

  counts:=adoquery2.RecordCount;

  //The number of records determines the number of rows in the table

  t:=doc.tables.Add(Wordapplication1.selection.range,counts+1,5);//5列

  t.cell(1,1).range.text:= 'unit ';

  t.Cell(1,1).Width:=120;

  t.cell(1,1).range.Paragraphs.Alignment:= wdAlignParagraphCenter;

  t.cell(1,2).range.text:= 'name ';

   ... ...

  //Write the headers of other fields in turn

  for i:=2 to counts+1 do

  begin

  t.cell(i,1).range.text:=adoquery2.field

  byname('dw').asstring;

  t.Cell(i,1).Width:=120;

  t.cell(i,1).range.Paragraphs.Alignment:=

   wdAlignParagraphCenter;

  t.cell(i,2).range.text:=adoquery2.field

  byname('xm').asstring;

  ... ...

  Adoquery2.next;

  End;

  Using Dephi to combine Word with the database, the automatic generation of user documents is realized, which greatly facilitates users.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324935900&siteId=291194637