如何提高从 C# 自动化打开 Microsoft Word 的性能?
我有 Microsoft Word 模板,我从应用程序中自动填充其字段,当用户请求打印时,我打开此模板。
但是,每次用户在填写字段后请求打印时创建 Word 应用程序的成本非常高,并且可能会导致打开模板时出现一些延迟。因此,我选择缓存对 Word 的引用,然后打开新填充的模板。
这解决了性能问题,因为打开文件比每次重新创建 Word 更便宜,但这仅在用户关闭文档而不是整个 Word 应用程序时才有效。发生这种情况时,我对 Word 的引用将变得无效并返回异常:在下一个打开模板的请求时“RPC 服务器不可用”。我尝试订阅 BeforeClosing
事件,但这会触发退出 Word 以及关闭文档。
我的问题是如何知道 Word 是否正在关闭文档或退出整个应用程序,以便我采取适当的操作,或者是否有任何关于提高打开 Word 模板性能的另一个思考方向的提示。
I have Microsoft Word template that I automated filling it's fields from my application, and when the user requests to print I open this template.
But creating the Word application every time a user requests to print after filling fields is very expensive and can lead to some delay while opening the template. So I choose to cache the reference to Word then just open the new filled template.
That solved the performance issue as opening the file is less expensive than recreating Word each time, but this only works when the user just closes the document not the entire Word application. When this happens my reference to Word becomes invalid and returns with exception: "The RPC server is unavailable" upon the next request of opening the template. I tried to subscribe to the BeforeClosing
event but this triggers quitting Word as well as closing documents.
My question is how to know if the Word is closing a document or quitting the entire application so I take the proper action, or any hint for another direction of thinking about improving the performance of opening a Word template.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不熟悉如何正确订阅 Word 关闭事件。但您似乎可以采取的一种选择是乐观地假设 Word 未关闭并使用您的缓存路径。在较高级别上捕获关闭 Word 时引发的
Exception
类型。如果遇到此异常,请删除对 word 的引用并像第一次发生一样重复该操作。通过这种方式,您不会一直获得缓存。但是您将能够利用用户仅关闭文档的情况。
I'm unfamiliar with how to properly subscribe to the Word closing events. But it seems like one option you could take is to optimistically assume that Word is not closed and use your caching route. At a high level catch the
Exception
type thrown when Word is closed. If you encounter this exception, remove your reference to word and repeat the operation like it was happening for the first time.You won't get the caching all of the time this way. But you will be able to take advantage of situations where the user only closes the document.