如何更新内置的Excel文档属性(文档元数据)

using Excel = Microsoft.Office.Interop.Excel; 

我正在使用下面的方法添加一个自定义属性,但它显示exception如果属性已经存在。 我想添加自定义属性,如果它存在它应该更新。

这里是我用来添加属性的代码

  Excel.Workbook workBk; Application _excelApp; public void SetDocumentProperty(string propertyName, string propertyValue) { try { _excelApp = new Application(); workBk = _excelApp.Workbooks.Open(@"C:\12345.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); object oDocCustomProps = workBk.CustomDocumentProperties; Type typeDocCustomProps = oDocCustomProps.GetType(); object[] oArgs = {propertyName,false, MsoDocProperties.msoPropertyTypeString, propertyValue}; typeDocCustomProps.InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, oDocCustomProps, oArgs); workBk.Save(); } finally { workBk.Close(false, @"C:\12345.xlsx", null); Marshal.ReleaseComObject(workBk); } } 

试试这一个

  public void SetDocumentProperty(string propertyName, string propertyValue) { try { _excelApp = new Application(); workBk = _excelApp.Workbooks.Open(@"C:\12345.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); object oDocCustomProps = workBk.CustomDocumentProperties; Type typeDocCustomProps = oDocCustomProps.GetType(); object[] oArgs = {propertyName,false, MsoDocProperties.msoPropertyTypeString, propertyValue}; typeDocCustomProps.InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, oDocCustomProps, oArgs); } catch { object customProperties = workBk.CustomDocumentProperties; Type customPropertiesType = customProperties.GetType(); // Retrieve the specific custom property item object customPropertyItem = customPropertiesType.InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty, null, customProperties, new object[] { propertyName }); Type propertyNameType = customPropertyItem.GetType(); propertyNameType.InvokeMember("Value", BindingFlags.Default | BindingFlags.SetProperty, null, customPropertyItem, new object[] { propertyValue }); } finally { workBk.Save(); workBk.Close(false, @"C:\12345.xlsx", null); Marshal.ReleaseComObject(workBk); } }