原理是一样的。当需要使用 Office“互操作”时,对如何使用 PInvoke 进行一些研究将会有所帮助。为了使用它,需要充分认识您需要解决的 Office 对象模型的部分:对象、属性或方法以及确切需要哪些参数,因为没有 IntelliSense 可以提供帮助。首先在 VBA 界面中进行测试可以使这变得更容易。
我在测试项目中拥有的以下代码片段演示了如何寻址单个文档属性并读取然后写入其值。请注意,示例代码适用于BuiltInDocumentProperties
。这可以更改为CustomDocumentProperties
如果这就是所需要的。
private void btnUpdateCustomDocProp_Click(object sender, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.application");
Excel.Workbook wb = xlApp.ActiveWorkbook;
object docProps = wb.BuiltinDocumentProperties;
object prop = ExistsDocProp("Author", docProps);
if (prop!=null)
{
object oProp = prop;
Type oPropType = oProp.GetType();
//read current value
string propValue = oPropType.InvokeMember("Value",
BindingFlags.GetProperty | BindingFlags.Default,
null, oProp, new object[] { }).ToString();
object oPropValue = "new test author";
//write new value
oPropType.InvokeMember("Value",
BindingFlags.SetProperty | BindingFlags.Default,
null, oProp, new object[] {oPropValue});
MessageBox.Show(propValue + ", " + oPropValue.ToString());
}
}
private object ExistsDocProp(string propName, object props)
{
Office.DocumentProperty customDocProp = null;
Type docPropsType = props.GetType();
object nrProps;
object itemProp = null;
object oPropName;
nrProps = docPropsType.InvokeMember("Count",
BindingFlags.GetProperty | BindingFlags.Default,
null, props, new object[] { });
int iProps = (int)nrProps;
for (int counter = 1; counter <= ((int)nrProps); counter++)
{
itemProp = docPropsType.InvokeMember("Item",
BindingFlags.GetProperty | BindingFlags.Default,
null, props, new object[] { counter });
oPropName = docPropsType.InvokeMember("Name",
BindingFlags.GetProperty | BindingFlags.Default,
null, itemProp, new object[] { });
if (propName == oPropName.ToString())
{
break;
}
}
return itemProp;
}