【发布时间】:2018-03-27 02:54:49
【问题描述】:
拥有一组 Word 模板(文件 *.dot)和一个小程序,可以根据该模板创建新文件。它工作正常,但目标是在一个 exe 文件中完成所有工作。 我看到解决方案是将模板文件移动到程序资源中。但我不知道,我将如何从资源中读取它们。请告诉我,如何做到这一点。 也许你可以给我另一个解决方案。
现在,我的代码是:
procedure TfmMain.CreateDocument0;
var
TempleateFileName: string;
WordApp, Document: OleVariant;
procedure FillBookmark(BookmarkName, bText: string);
var
Range: OleVariant;
begin
if Document.Bookmarks.Exists(BookmarkName) then
begin
Range := Document.Bookmarks.Item(BookmarkName).Range;
Range.Text := bText;
end;
end;
begin
TempleateFileName := ExtractFilePath(Application.ExeName)+'Templates\0.dot';
try
WordApp := GetActiveOleObject('Word.Application');
except
try
WordApp := CreateOleObject('Word.Application');
except
on E: Exception do
begin
MessageBox(Self.Handle, PChar(E.Message), PChar(fmMain.Caption), MB_OK+MB_ICONERROR);
Exit;
end;
end;
end;
try
Document := WordApp.Documents.Add(TempleateFileName, False);
FillBookmark('ObjectType', edt0ObjectType.Text);
...
WordApp.Visible := True;
WordApp.Activate;
finally
WordApp := Unassigned;
end;
end;
也就是说,我应该改变这一行:
Document := WordApp.Documents.Add(TempleateFileName, False);
不是从文件中读取,而是从程序资源中读取。
【问题讨论】:
-
两个步骤。 1. 将文件作为编译资源添加到您的可执行文件中。 2. 在运行时提取文件并将它们保存到磁盘。此时 Excel 能够读取文件,您可以像以前一样继续。
-
是的,大卫,我考虑过这一点,但该变体有一些限制。如果我找不到其他解决方案,将使用它。
-
如果必须不将文件存储在 HDD/SSD 上,请考虑使用 RAM 磁盘。或者考虑将文件存储为 *.rtf 格式并将其提供给 TRichEdit。
-
OT:关于
MessageBox(Self.Handle, PChar(E.Message), PChar(fmMain.Caption), MB_OK+MB_ICONERROR);-Self.之前的Handle是多余的,但没有害处。但通常你不应该在TfrmMain的方法中引用frmMain。 -
而
MB_OK+MB_ICONERROR最好是MB_OK or MB_ICONERROR,因为您想组合位掩码。