我试图让FreePascal打开一个word文档,将一些文本和数据附加到它然后关闭它。我已经设法连接并且可以在文档中写一行,但是任何事情都会让我失望。目前我在this Visual Basic reference尝试方法细节,这与我期望FreePascal处理事物的方式非常相似。
基本上我认为我误解了Lazarus和Word OLE之间的关系是如何工作的,有人能为我提供关于如何构建一个我可以构建的简单文档的示例吗?
以下代码打开文档,然后完全替换其内容
program officAuto;
{$IFDEF FPC}
{$MODE Delphi}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils, Variants, ComObj;
const
ServerName = 'Word.Application';
var
Server, Doc : Variant;
oPara : Variant;
w:widestring;
begin
if Assigned(InitProc) then
TProcedure(InitProc);
try
Server := CreateOleObject(ServerName);
except
WriteLn('Unable to start Word.');
Exit;
end;
w:= UTF8Decode('c:\mydoc.docx');
Server.Visible := True; {Make Word visible}
Doc := Server.Documents.Open(w);
Doc.Range.Text := 'This is a Heading';
Doc.Range.Font.Bold := True;
Doc.Format.SpaceAfter := 24;
end.
然而,根据上面的代码,在尝试在书签上打印字符串时,打开文档,保留内容,移动到书签然后什么都不做。
w:= UTF8Decode('c:\mydoc.docx');
Server.Visible := True;
Doc := Server.Documents.Open(w);
oPara := Doc.Content.Paragraphs.Add(Doc.Bookmarks.Item('\Bookmark1').Range);
oPara := Doc.Range.Text('Where will this appear if at all!');
答案 0 :(得分:0)
program officAuto;
{$IFDEF FPC}
{$MODE Delphi}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils, Variants, ComObj;
var
Server, Connect : Variant;
oWord, oPara1, oPara2 : Variant;
w:widestring;
begin
if Assigned(InitProc) then
TProcedure(InitProc);
try
Server := CreateOleObject('Word.Application');
except
WriteLn('Unable to start Word.');
Exit;
end;
// oWord := Server.Documents.Add;
w:= UTF8Decode('c:\mydoc.docx');
Server.Visible := True;
Server.Documents.Open(w);
oPara1 := Server.ActiveDocument.Content.Paragraphs.Add;
oPara1.Range.Text := 'This is a Heading';
oPara1.Range.Font.Bold := True;
oPara1.Format.SpaceAfter := 24;
oPara1.Range.InsertParagraphAfter();
oPara2 := Server.ActiveDocument.Content.Paragraphs.Add;
oPara2.Range.Text := 'Where will this appear if at all!';
oPara2.Range.Font.Bold := False;
oPara2.Format.SpaceAfter := 24;
oPara2.Range.InsertParagraphAfter();
end.