Interop Word - 从文档中删除页面
使用 Word 互操作库从文档对象中删除特定页面的最简单、最有效的方法是什么?
我注意到有一个 Pages 属性扩展/实现了 IEnumerable。是否可以简单地删除数组中的元素,然后页面就会从文档中删除?
我还看过范围和部分示例,但使用起来看起来不太优雅。
谢谢。
What is the easiest and most efficient way to delete a specific page from a Document object using the Word Interop Libraries?
I have noticed there is a Pages property that extends/implements IEnumerable. Can one simply remove the elements in the array and the pages will be removed from the Document?
I have also seen the Ranges and Section examples, but the don't look very elegant to use.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对您问题的简短回答是,没有优雅的方式来实现您想要实现的目标。
Word 将文档的内容与其布局严格分开。就Word 而言,文档没有页面,只有页面。相反,页面是通过以某种方式查看文档(例如打印视图)而从文档派生出来的东西。
Pages
集合属于Pane
接口(例如,通过Application.ActiveWindow.ActivePane
访问),它控制布局。因此,Page
上没有任何方法允许您更改(或删除)导致页面存在的内容。如果您可以控制代码中正在处理的文档,我建议您在文档中定义代表要以编程方式删除的部分的部分。节是一种更好的结构,因为它们代表内容,而不是布局(节可能包含分页符)。如果您要执行此操作,可以使用以下代码删除特定部分:
The short answer to your question is that there is no elegant way to do what you are trying to achieve.
Word heavily separates the content of a document from its layout. As far as Word is concerned, a document doesn't have pages; rather, pages are something derived from a document by viewing it in a certain way (e.g. print view). The
Pages
collection belongs to thePane
interface (accessed, for example, byApplication.ActiveWindow.ActivePane
), which controls layout. Consequently, there are no methods onPage
that allow you to change (or delete) the content that leads to the existence of the page.If you have control over the document(s) that you are processing in your code, I suggest that you define sections within the document that represent the parts you want to programmatically delete. Sections are a better construct because they represent content, not layout (a section may, in turn, contain page breaks). If you were to do this, you could use the following code to remove a specific section:
一种可能的选择是为整个页面添加书签(选择整个页面,转到“工具”|“插入书签”,然后输入名称)。然后,您可以使用 Document 对象的 Bookmarks 集合来引用文本并将其删除。
或者,尝试与此代码等效的 C#:
第一行将光标移动到页“PageNumber”。第二个使用预定义书签,它始终引用光标当前所在的页面,包括页面末尾的分页符(如果存在)。
One possible option is to bookmark the whole pages (Select the whole page, go to Tools | Insert Bookmark then type in a name). You can then use the Bookmarks collection of the Document object to refer to the text and delete it.
Alternatively, try the C# equivalent of this code:
The first line moves the cursor to page "PageNumber". The second one uses a Predefined Bookmark which always refers to the page the cursor is currently on, including the the page break at the end of the page if it exists.