How to Search and Replace in odt Open Office document?

◇◆丶佛笑我妖孽 提交于 2019-11-28 01:13:20

问题


In my Delphi application I am currently do Search&Replace programmatically for doc and docx word documents using office ole automation. Does anyone has the code to do the same (for doc, docs, odt) in OpenOffice?

I also asked a related question on saving to pdf.


回答1:


You should take a focus on XReplaceable interface. Here is the example. Please note, that there's no error handling. I've tested it with LibreOffice writer and it works fine for me.

uses
  ComObj;

procedure OpenOfficeReplace(const AFileURL: string; ASearch: string; const AReplace: string);
var
  StarOffice: Variant;
  StarDesktop: Variant;
  StarDocument: Variant;
  FileReplace: Variant;
  FileParams: Variant;
  FileProperty: Variant;

begin
  StarOffice := CreateOleObject('com.sun.star.ServiceManager');
  StarDesktop := StarOffice.CreateInstance('com.sun.star.frame.Desktop');

  FileParams := VarArrayCreate([0, 0], varVariant);
  FileProperty := StarOffice.Bridge_GetStruct('com.sun.star.beans.PropertyValue');
  FileProperty.Name := 'Hidden';
  FileProperty.Value := False;
  FileParams[0] := FileProperty;

  StarDocument := StarDesktop.LoadComponentFromURL(AFileURL, '_blank', 0, FileParams);

  FileReplace := StarDocument.CreateReplaceDescriptor;
  FileReplace.SearchCaseSensitive := False;
  FileReplace.SetSearchString(ASearch);
  FileReplace.SetReplaceString(AReplace);

  StarDocument.ReplaceAll(FileReplace);

  ShowMessage('Replace has been finished');

  StarDocument.Close(True);
  StarDesktop.Terminate;
  StarOffice := Unassigned;
end;

And the usage of the example

procedure TForm1.Button1Click(Sender: TObject);
begin
  OpenOfficeReplace('file:///C:/File.odt', 'Search', 'Replace');
end;

There are also several search/replace options for SearchDescriptor.



来源:https://stackoverflow.com/questions/7806041/how-to-search-and-replace-in-odt-open-office-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!