Thema: Delphi Replace string in *.docx

Einzelnen Beitrag anzeigen

danten

Registriert seit: 19. Feb 2012
Ort: Czech Republic, Prag
126 Beiträge
 
Delphi 10.1 Berlin Architect
 
#1

Replace string in *.docx

  Alt 28. Mär 2015, 08:26
Hi all,
I need to change the text in the text box.
This procedure changes only plain text.
Delphi-Quellcode:
function Word_StringReplace(ADocument: TFileName; Ss, Rs: string; Flags: TWordReplaceFlags): Boolean;
const
  wdFindContinue = 1;
  wdReplaceOne = 1;
  wdReplaceAll = 2;
  wdDoNotSaveChanges = 0;
var
  WordApp: OLEVariant;
begin
  Result := False;

  { Check if file exists }
  if not FileExists(ADocument) then
  begin
    ShowMessage('Specified Document not found.');
    Exit;
  end;

  { Create the OLE Object }
  try
    WordApp := CreateOLEObject('Word.Application');
  except
    on E: Exception do
    begin
      E.Message := 'Word is not available.';
      raise;
    end;
  end;

  try
    { Hide Word }
    WordApp.Visible := False;
    { Open the document }
    WordApp.Documents.Open(ADocument);
    { Initialize parameters}
    WordApp.Selection.Find.ClearFormatting;
    WordApp.Selection.Find.Text := Ss;
    WordApp.Selection.Find.Replacement.Text := Rs;
    WordApp.Selection.Find.Forward := True;
    WordApp.Selection.Find.Wrap := wdFindContinue;
    WordApp.Selection.Find.Format := True;
    WordApp.Selection.Find.MatchCase := wrfMatchCase in Flags;
    WordApp.Selection.Find.MatchWholeWord := True;
    WordApp.Selection.Find.MatchWildcards := wrfMatchWildcards in Flags;
    WordApp.Selection.Find.MatchSoundsLike := False;
    WordApp.Selection.Find.MatchAllWordForms := False;
WordApp.Selection.Find. ????????????????????? TextBox ???????

Delphi-Quellcode:
    { Perform the search}
    if wrfReplaceAll in Flags then
      WordApp.Selection.Find.Execute(Replace := wdReplaceAll)
    else
      WordApp.Selection.Find.Execute(Replace := wdReplaceOne);
    { Save word }
    WordApp.ActiveDocument.SaveAs(ADocument);
    { Assume that successful }
    Result := True;
    { Close the document }
    WordApp.ActiveDocument.Close(wdDoNotSaveChanges);
  finally
    { Quit Word }
    WordApp.Quit;
    WordApp := Unassigned;
  end;
end;
Example
Word_StringReplace('mydoc.docx','<fname_lname>','M y Name',[wrfReplaceAll]);
Miniaturansicht angehängter Grafiken
word.png  
Daniel
  Mit Zitat antworten Zitat