Sto tentando di aggiungere proprietà personalizzate a una cartella di lavoro che ho creato a livello di programmazione. Ho un metodo per ottenere e impostare le proprietà, ma il problema è che la cartella di lavoro restituisce null per la proprietà CustomDocumentProperties. Non riesco a capire come inizializzare questa proprietà in modo che possa aggiungere e recuperare proprietà dalla cartella di lavoro. Microsoft.Office.Core.DocumentProperties è un'interfaccia, così non posso andare a fare la seguenteAccesso alle proprietà del documento personalizzato di Excel a livello di programmazione
if(workbook.CustomDocumentProperties == null)
workbook.CustomDocumentProperties = new DocumentProperties;
Ecco il codice che ho per ottenere e impostare le proprietà:
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);
}
La linea proprietà = workBk.CustomDocumentProperties come DocumentProperties; imposta sempre le proprietà su null.
Questo sta usando Microsoft.Office.Core v12.0.0.0 e Microsoft.Office.Interop.Excell v12.0.0.0 (Office 2007)
Esattamente il link che ho trovato, e ho postato il mio codice mentre si stavano scrivendo questo. +1 e accettato per te :-) –
Aggiornamento per il collegamento su "perché": https://support.microsoft.com/en-us/kb/303296 –