系统环境:Windows XP SP3;
编程环境:Microsoft Visual Studio 2008;
Office版本:Office 2007。
一、开始编写这个程序先添加几个命名空间:
using Word = Microsoft.Office.Interop.Word;//这个自然是不用说的了。
using Microsoft.Office.Core;//添加了Office (12.0版)就会有这个了。
using System.Reflection;//使用Missing.Value时就要用到这个命名空间。
二、添加几个全局变量
Word.Application oWord;
Word._Document oDoc;
object oMissing = Missing.Value;
object oDocBuiltInProps;
object oDocCustomProps;
三、在新建的Form中加一个button1按钮,在其Click事件中写入以下代码:
private void button1_Click(object sender, EventArgs e)
{
//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, "Autor");
//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 \"Property\" 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);
}
浙公网安备 33010602011771号