如何在odt Open Office文档中搜索和替换?

时间:2011-10-18 10:48:19

标签: delphi openoffice.org replace docx odt

在我的Delphi应用程序中,我目前使用office ole自动化以编程方式对doc和docx word文档进行搜索和替换。有没有人在OpenOffice中有相同的代码(对于doc,docs,odt)?

我还问过related question on saving to pdf

1 个答案:

答案 0 :(得分:7)

您应该关注XReplaceable界面。这是一个例子。请注意,没有错误处理。我已经用LibreOffice编写器对它进行了测试,它对我来说很好。

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;

使用示例

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

SearchDescriptor还有几个搜索/替换选项。