添加對(duì)?Microsoft Word 對(duì)象庫的引用。為此,請(qǐng)按照下列步驟操作:
在項(xiàng)目菜單上,單擊添加引用。
在?COM?選項(xiàng)卡上,找到?Microsoft Word 對(duì)象庫,然后單擊選擇。
注意:Microsoft Office 2003 包含主 Interop 程序集 (PIA)。 Microsoft Office XP 不包含 PIA,但您可以下載 PIA。 有關(guān) Office XP PIA 的其他信息,請(qǐng)單擊下面的文章編號(hào),以查看 Microsoft 知識(shí)庫中相應(yīng)的文章: 328912?INFO:Microsoft Office XP PIA 可供下載
在代碼窗口中,將以下代碼 private void button1_Click(object sender, System.EventArgs e)
{
} 替換為: private void button1_Click(object sender, System.EventArgs e)
{Word.Application oWord;Word._Document oDoc;object oMissing = Missing.Value;object oDocBuiltInProps;object oDocCustomProps;//Create an instance of Microsoft Word and make it visible.oWord = new Word.Application();oWord.Visible = true;//Create a new Document and get the BuiltInDocumentProperties collection.oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);oDocBuiltInProps = oDoc.BuiltInDocumentProperties;Type typeDocBuiltInProps = oDocBuiltInProps.GetType();//Get the Author property and display it.string strIndex = "Author";string strValue;object oDocAuthorProp = typeDocBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty, null,oDocBuiltInProps, new object[] {strIndex} );Type typeDocAuthorProp = oDocAuthorProp.GetType();strValue = typeDocAuthorProp.InvokeMember("Value", BindingFlags.Default |BindingFlags.GetProperty,null,oDocAuthorProp,new object[] {} ).ToString();MessageBox.Show( "The Author is: " + strValue,"Author" );//Set the Subject property.strIndex = "Subject";strValue = "The Subject";typeDocAuthorProp.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null,oDocBuiltInProps, new object[] {strIndex,strValue} );//Add a property/value pair to the CustomDocumentProperties collection.oDocCustomProps = oDoc.CustomDocumentProperties;Type typeDocCustomProps = oDocCustomProps.GetType();strIndex = "Knowledge Base Article";strValue = "Q303296";object[] oArgs = {strIndex,false,MsoDocProperties.msoPropertyTypeString,strValue};typeDocCustomProps.InvokeMember("Add",BindingFlags.Default | BindingFlags.InvokeMethod, null, oDocCustomProps, oArgs );MessageBox.Show("Select \"Properties\" from the File menu "+ "to view the changes.\nSelect the Summary tab to view "+ "the Subject property and the Custom tab to view the Knowledge" + "Base Article property.", "Check File Properties",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
滾動(dòng)到代碼窗口頂部,然后將以下行添加到?using?指令列表的末尾: using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;