Я использую электронную таблицу OpenXML для создания файла .xlsx с заданным шаблоном и словарем переменных. Но у меня есть вопрос при обновлении значения в SharedStringTable, поскольку InnerText SharedStringItem доступен только для чтения. Мой файл шаблона Excel представляет собой файл с расширением .xlsx. Переменные, которые мне нужно заменить, имеют префикс «$$$». Например, "$$$abc", то в словаре у меня может быть пара ‹"abc", "Payson"> (если в словаре нет ключа "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];
}
}
}
}
Документ находится здесь http://msdn.microsoft.com/en-us/library/documentformat.openxml.openxmlcompositeelement.innertext(v=office.14).aspx
Даже в документе упоминается, что внутренний текст может быть установлен, однако нет метода доступа set. Кто-нибудь знает, как установить InterText. Поскольку у меня может быть много ячеек с одинаковым именем переменной «$$$abc», и я хотел бы заменить их все на «Payson».