我需要将长(特定于文档)字符串保存到Excel文档中。 由于Office.Core.CustomDocumentProperty.value的长度限制仅为255个字符,因此请告知如何克服此限制,或建议在Excel文档中存储数据的其他方法。
(对我来说,一个单元格公式只能存储255个字符,所以这不是一个可行的解决方案。)
答案 0 :(得分:3)
只需将您的值拆分为多个属性即可。这样的事情会起作用。
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();
}
根据字符串的大小,这可能会非常慢。更好的选择可能是使用自定义XML部件。 (我高度建议将命名空间"urn:custom-storage:XXX"
更改为独特且专有的内容,以免与使用相同技术编写的其他软件相冲突。)
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.");
}
}