【问题标题】:How to Search and Replace in odt Open Office document?如何在 odt Open Office 文档中进行搜索和替换?
【发布时间】:2011-10-18 10:48:19
【问题描述】:

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

我还问了related question on saving to pdf

【问题讨论】:

标签: delphi openoffice.org replace docx odt


【解决方案1】:

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

【讨论】:

  • 太棒了,一个人必须习惯 // 而不是 \ 但它很好用!
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 2017-01-05
  • 2020-08-09
  • 1970-01-01
  • 2015-02-15
  • 2023-04-07
  • 2010-10-22
  • 2011-06-15
相关资源
最近更新 更多