[英]OpenXML Spreadsheet update value in SharedStringTable
我使用OpenXML Spreadsheet來生成具有給定模板和變量字典的.xlsx文件。 但是我在更新SharedStringTable中的值時有一個問題,因為SharedStringItem的InnerText是只讀的。 我的模板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];
}
}
}
}
即使文檔提到可以設置內部文本,但是也沒有設置訪問器。 有誰知道如何設置InnterText。 由於我可能有許多具有相同變量名“ $$$ abc”的單元格,因此我想將它們全部替換為“ Payson”。
看來您需要替換InnerXml,然后保存SharedStringTable。 請參閱在.net中使用SharedStringTable和xml sdk設置文本值 。
我試圖編輯文本,它可以工作。
Text newText = new Text();
newText.Text = dictionary[variableName];
item.Text = newText;
stringTable.Save();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.