【发布时间】:2014-01-25 00:35:38
【问题描述】:
我正在使用 OpenXML 电子表格来生成具有给定模板和变量字典的 .xlsx 文件。但是在更新 SharedStringTable 中的值时我有一个问题,因为 SharedStringItem 的 InnerText 是只读的。 我的模板 excel 文件是一个带有 .xlsx 的文件。我需要替换的变量具有前缀“$$$”。例如,“$$$abc”,那么在字典中我可能有 对(如果字典不包含键 "abc",则将 "$$$abc" 留在那里. 我所做的是这样的
private void UpdateValue(WorkbookPart wbPart, Dictionary<string, string> dictionary)
{
var stringTablePart = wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
if (stringTablePart == null)
{
stringTablePart = wbPart.AddNewPart<SharedStringTablePart>();
}
var stringTable = stringTablePart.SharedStringTable;
if (stringTable == null)
{
stringTable = new SharedStringTable();
}
//iterate through all the items in the SharedStingTable
// if there is any text starts with $$$, find out the name of the string
// look for the string in the dictionary
// replace it if found, or keep it if not.
foreach (SharedStringItem item in stringTable.Elements<SharedStringItem>())
{
if (item.InnerText.StartsWith("$$$"))
{
string variableName = item.InnerText.Substring(3);
if (!string.IsNullOrEmpty(variableName) && dictionary.containsKey(variableName))
{
// The problem is here since InnerText is read only.
item.InnerText = dictionary[variableName];
}
}
}
}
即使文档提到可以设置内部文本,但是没有设置访问器。 有谁知道如何设置InterText。由于我可能有许多具有相同变量名称“$$$abc”的单元格,我想将它们全部替换为“Payson”。
【问题讨论】: