[英]OpenXML Spreadsheet update value in SharedStringTable
I am using OpenXML Spreadsheet in order to generate .xlsx file with a given template and a variable dictionary. 我使用OpenXML Spreadsheet来生成具有给定模板和变量字典的.xlsx文件。 But I have a question when updating the value in SharedStringTable since the InnerText of the SharedStringItem is read only.
但是我在更新SharedStringTable中的值时有一个问题,因为SharedStringItem的InnerText是只读的。 My template excel file is a file with .xlsx.
我的模板excel文件是带有.xlsx的文件。 The variables I need to replace has prefix "$$$".
我需要替换的变量的前缀为“ $$$”。 For example, "$$$abc", then in the dictionary I may have <"abc", "Payson"> pair (if the dictionary does not contain the key "abc", just leave the "$$$abc" there. What I have done is something like this
例如,“ $$$ 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];
}
}
}
}
The document is here http://msdn.microsoft.com/en-us/library/documentformat.openxml.openxmlcompositeelement.innertext(v=office.14).aspx 该文档位于http://msdn.microsoft.com/zh-cn/library/documentformat.openxml.openxmlcompositeelement.innertext(v=office.14).aspx
Even the document mentioned that innertext can be set, however, there is no set accessor. 即使文档提到可以设置内部文本,但是也没有设置访问器。 Does anyone know how to set the InnterText.
有谁知道如何设置InnterText。 Since I may have many cells with the same variable name "$$$abc", and I would like to replace all of them with "Payson".
由于我可能有许多具有相同变量名“ $$$ abc”的单元格,因此我想将它们全部替换为“ Payson”。
It appears that you need to replace the InnerXml, then save the SharedStringTable. 看来您需要替换InnerXml,然后保存SharedStringTable。 See Set text value using SharedStringTable with xml sdk in .net .
请参阅在.net中使用SharedStringTable和xml sdk设置文本值 。
I've tried to edit the Text and it works. 我试图编辑文本,它可以工作。
Text newText = new Text();
newText.Text = dictionary[variableName];
item.Text = newText;
stringTable.Save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.