问题
I need to save long (,document specific) string to an Excel document. Since the length limit for Office.Core.CustomDocumentProperty.value is only 255 char, please advise on how to overcome this limit, or suggesting other ways to store data in an Excel document.
(To my recollection, a cell formula can only store 255 char, so this is not a workable solution.)
回答1:
Just split your value into multiple properties. Something like this would work.
private static void WriteCustomDocumentProperty(Workbook workbook, string name, string value)
{
dynamic customDocumentProperties = workbook.CustomDocumentProperties;
var numParts = value.Length/255 + (value.Length%255 != 0 ? 1 : 0);
for (var i = 0; i < numParts; ++i)
{
var part = value.Substring(i*255, Math.Min(255, value.Length - i*255));
customDocumentProperties.Add(name + "." + i, false, MsoDocProperties.msoPropertyTypeString, part);
}
customDocumentProperties.Add(name + ".Count", false, MsoDocProperties.msoPropertyTypeNumber, numParts);
}
private static string ReadCustomDocumentProperty(Workbook workbook, string name)
{
dynamic customDocumentProperties = workbook.CustomDocumentProperties;
var numParts = Convert.ToInt32(customDocumentProperties[name + ".Count"].Value);
var value = new StringBuilder();
for (var i = 0; i < numParts; ++i)
value.Append(customDocumentProperties[name + "." + i].Value);
return value.ToString();
}
Depending on the size of your strings, this may be very slow. A better option might be to use Custom XML Parts. (I highly recommend changing the namespace "urn:custom-storage:XXX"
to something unique and proprietary, lest you run afoul of another software written using this same technique.)
private static void WriteCustomDocumentProperty(Workbook workbook, string name, string value)
{
var ns = "urn:custom-storage:" + name;
var document = new XDocument(new XElement(XName.Get("custom-storage", ns), value));
var xmlValue = document.ToString();
workbook.CustomXMLParts.Add(xmlValue);
}
private static string ReadCustomDocumentProperty(Workbook workbook, string name)
{
var ns = "urn:custom-storage:" + name;
var parts = workbook.CustomXMLParts.SelectByNamespace(ns);
switch (parts.Count)
{
case 0:
return null;
case 1:
return XDocument.Parse(parts[1].XML).Root.Value;
default:
throw new ApplicationException("Duplicate part in workbook.");
}
}
来源:https://stackoverflow.com/questions/42120915/how-to-overcome-custom-document-property-size-limit