5

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

我还询问了有关保存到 pdf 的相关问题

4

1 回答 1

8

您应该关注XReplaceable接口。这是示例。请注意,没有错误处理。我已经用 LibreOffice writer 对其进行了测试,它对我来说效果很好。

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还有几个搜索/替换选项。

于 2011-10-18T18:14:46.330 回答