2011-10-18 47 views
5

在我的Delphi應用程序中,我目前正在搜索&使用office ole自動化以編程方式替換doc和docx word文檔。有沒有人有代碼在OpenOffice中執行相同的操作(對於doc,docs,odt)?如何搜索和替換打開Office文檔?

我還問了一個related question on saving to pdf

+0

是否有一個用於處理docx文檔的delphi代碼? – none

+1

是的很多,你應該使用OLE自動化(ActievX)例如http://stackoverflow.com/questions/5484721/delphi-convert-doc-to-pdf-using-word-activex – LaBracca

回答

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

+0

偉大的,一個只是必須習慣//而不是\,但它很好用! – LaBracca

相關問題