How to set the file name of a word document withou

2019-02-23 16:21发布

问题:

I create word documents via automation and mailmerge with office Interop from c# (.net4). The merge works well and the user receives the created document as he desires. So far all is well. The client now requests, that if he tries to save the generated file (via save file dialog), that the filename of the document is already prefilled.

I already have tried the obvious things such as setting the Name property of the Document-instance and other properties, I also googled for a solution but up to now, I was not able to set the file-name of the word file (without saving it).

Does someone knows a way how to achieve this? I feel that the client would be very happy if it would work, and I also spent already a lot of time on this (I have to admit that word automation is a thing I have not a lot of experience).

回答1:

If you set the Title property of the document, when you choose Save As, that is the document name that will be used. You can also set the default save location. In VBA

Set doc = ActiveDocument

sTitle = doc.BuiltInDocumentProperties("Title").Value
doc.BuiltInDocumentProperties("Title").Value = "A different title"

However, this only works on the second (and later) save attempt(s). The first attempt will always use the title from the template, if any, or content from the first line of the document if none. See the end of this answer for a better solution.

Note, however, that you must make some change to the document before Save As for the new title to take effect.

Sub SetSummaryInfo()
Dim dp As Object
Dim sTitle As String
    If Documents.Count > 0 Then
       Set dp = Dialogs(wdDialogFileSummaryInfo)
       ' Retrieve value of "Title" into a variable.
       sTitle = dp.Title
       ' Set "Title" to a new value.
       dp.Title = "My Title"
       ' Set the value without showing the dialog.
       dp.Execute
       ' Save the changes
       'ActiveDocument.Save
    End If
End Sub

As remarked by HCL in C#, you can set the default filename (for the dialog only) using this code:

dynamic dialog = wordApp.Dialogs[WdWordDialog.wdDialogFileSummaryInfo]; 
dialog.Title = "MyTitle"; 
dialog.Execute();

This opens the standard "Save As" dialog, sets the default filename (not what you'd expect from a 'Title' property but that's what it does), and opens the dialog.



回答2:

The docs
http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas%28v=vs.80%29.aspx
seems to say that you CAN specify a filename or am I missing something?