I am using C# and Microsoft.Office.Interop.Word to perform the following
- Open a document
- Update the contents of the document
- Save and close the document
This works fine if the document is opened using this method where FileName is the filename, AddToRecentFiles is false and all else is Missing.Value
Document Open(
[In] ref object FileName,
[In, Optional] ref object ConfirmConversions,
[In, Optional] ref object ReadOnly,
[In, Optional] ref object AddToRecentFiles,
[In, Optional] ref object PasswordDocument,
[In, Optional] ref object PasswordTemplate,
[In, Optional] ref object Revert,
[In, Optional] ref object WritePasswordDocument,
[In, Optional] ref object WritePasswordTemplate,
[In, Optional] ref object Format,
[In, Optional] ref object Encoding,
[In, Optional] ref object Visible,
[In, Optional] ref object OpenAndRepair,
[In, Optional] ref object DocumentDirection,
[In, Optional] ref object NoEncodingDialog,
[In, Optional] ref object XMLTransform
);
The problem I am having is that I want the processing do be silent, that is I do not want to show the application to the user. This is easily done by letting Visible be false.
However if I set Visible to false, update, save and close the document, then the next time I open the document it will be opened in Draft mode. I do not wish for the view mode to be changed when updating the document. If my document was in Print Layout mode before my program processes it, I want it to remain in Print Layout mode the next time I open it.
Where I am at now, I have two choices:
Open the document with visible=true and keep the viewing mode. Open the document with visible=false and always set view mode to Draft.Does anyone have a third choice for me, a choice that lets me update the contents of the 开发者_如何转开发document without displaying the word application to the user?
You can switch back to the print layout view from code:
using Word = Microsoft.Office.Interop.Word;
// Option 1: via Application object
Word.Application app = new Word.Application();
app.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;
// Option 2: via Document object
Word.Document doc;
object objOne = 1;
doc.Windows.get_Item(ref objOne).View.Type = Word.WdViewType.wdPrintView;
VBA equivalent:
ActiveDocument.Windows(1).View = wdPrintView
It's best practice to backup the original view and then restore it when you are done with your automation task.
You didn't show your code, so we cannot know what modifications you exactly do. However, certain automation tasks like modifying headers/footers might require a certain view.
Did some more playing around with the parameters and it turned out that using
Visible=Missing.Value
instead of true
or false
would allow me to process the document silently and does not change the view type.
精彩评论