简体   繁体   中英

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. But I have a question when updating the value in SharedStringTable since the InnerText of the SharedStringItem is read only. My template excel file is a file with .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

        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

Even the document mentioned that innertext can be set, however, there is no set accessor. Does anyone know how to set the InnterText. Since I may have many cells with the same variable name "$$$abc", and I would like to replace all of them with "Payson".

It appears that you need to replace the InnerXml, then save the SharedStringTable. See Set text value using SharedStringTable with xml sdk in .net .

I've tried to edit the Text and it works.

               Text newText = new Text();
                newText.Text = dictionary[variableName];
                item.Text = newText;
                stringTable.Save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM