我想在Word 2007中增加导出到新文件格式的选项。最好能够在Word 2007另存为对话框的文件格式下拉框中选择这个选项。尽管我有很多.NET经验,但我并没有为MS Office进行过太多开发。从高层次上讲,我应该如何使用.NET向Word 2007添加另一个保存为格式?
在Word 2007中,您基本上有两种选项来添加自己的自定义文件导出过滤器:
从Office 2007 SP2开始,您可以包含基于OpenXML的导出过滤器,请参见介绍适用于2007 Microsoft Office System SP2的Open XML格式外部文件转换器了解详情。
对于所有版本的Word(返回到Word 97甚至更早),您可以使用实现为Win32 dll的基于RTF的导出过滤器:如何获取WinWord转换器SDK(GC1039)
Microsoft.Office.Core.FileDialog
接口及其 Filters
属性(类型为 Microsoft.Office.Core.FileDialogFilters
),您可以在其中添加和删除筛选器。它们包含在 Visual Studio Tools for Office 12 中,位于 Office.dll 中。FileDialog
对象,首先获取 Microsoft.Office.Interop.Word.Application 实例(通常是通过创建新的 ApplicationClass
或等效地使用 VBA 的 CreateObject
)并将其命名为 application
。然后执行以下操作:Microsoft.Office.Core.FileDialog dialog = application.get_FileDialog( Microsoft.Office.Core.MsoFileDialogType.msoFileDialogSaveAs );
dialog.Title = "Your Save As Title";
// Set any other properties
dialog.Filters.Add( /* You Filter Here */ );
// Show the dialog with your format filter
if( dialog.Show() != 0 && fileDialog.SelectedItems.Count > 0 )
{
// Either call application.SaveAs( ... ) or use your own saving code.
}
实际的代码可以是一个COM插件,或者是使用COM打开/与Word交互的外部程序。关于替换内置的"另存为"对话框,您还需要在某个地方(VBA、使用此代码等)处理Microsoft.Office.Interop.Word.Application.DocumentBeforeSave事件以拦截默认行为。
这里是一个"另存为"处理器的示例:
private void application_DocumentBeforeSave( Microsoft.Office.Interop.Word.Document document, ref bool saveAsUI, ref bool cancel )
{
// Be sure we are only handling our document
if( document != myDocument )
return;
// Allow regular "Save" behavior, when not showing the "Save As" dialog
if( !saveAsUI )
return;
// Do not allow the default UI behavior; cancel the save and use our own method
saveAsUI = false;
cancel = true;
// Call our own "Save As" method on the document for custom UI
MySaveAsMethod( document );
}
无法通过对象模型保存到自定义格式或更改SaveAs对话框。目前,这似乎是唯一的方法http://msdn.microsoft.com/en-us/library/aa338206.aspx
System.Windows.Forms.SaveFileDialog
。 - Joe