我試圖將自定義屬性添加到我以編程方式創建的工作簿。我有一個方法來獲取和設置屬性,但問題是工作簿正在爲CustomDocumentProperties屬性返回null。我無法弄清楚如何初始化此屬性,以便我可以從工作簿中添加和檢索屬性。 Microsoft.Office.Core.DocumentProperties是一個接口,所以我不能去,然後執行以下以編程方式訪問Excel自定義文檔屬性
if(workbook.CustomDocumentProperties == null)
workbook.CustomDocumentProperties = new DocumentProperties;
這裏是我得和設置屬性代碼:
private object GetDocumentProperty(string propertyName, MsoDocProperties type)
{
object returnVal = null;
Microsoft.Office.Core.DocumentProperties properties;
properties = (Microsoft.Office.Core.DocumentProperties)workBk.CustomDocumentProperties;
foreach (Microsoft.Office.Core.DocumentProperty property in properties)
{
if (property.Name == propertyName && property.Type == type)
{
returnVal = property.Value;
}
DisposeComObject(property);
}
DisposeComObject(properties);
return returnVal;
}
protected void SetDocumentProperty(string propertyName, string propertyValue)
{
DocumentProperties properties;
properties = workBk.CustomDocumentProperties as DocumentProperties;
bool propertyExists = false;
foreach (DocumentProperty prop in properties)
{
if (prop.Name == propertyName)
{
prop.Value = propertyValue;
propertyExists = true;
}
DisposeComObject(prop);
if(propertyExists) break;
}
if (!propertyExists)
{
properties.Add(propertyName, false, MsoDocProperties.msoPropertyTypeString, propertyValue, Type.Missing);
}
DisposeComObject(propertyExists);
}
線 性質= workBk.CustomDocumentProperties作爲DocumentProperties; 總是將屬性設置爲null。
這是使用Microsoft.Office.Core v12.0.0.0和Microsoft.Office.Interop.Excell v12.0.0.0(Office 2007中)
準確地說,我找到了這個鏈接,並且當您發佈此內容時我發佈了我的代碼。 +1並接受爲您:-) – 2009-07-16 14:18:46
更新以鏈接「爲什麼」:https://support.microsoft.com/zh-cn/kb/303296 – 2016-02-09 18:18:37