【问题标题】:OpenXML Spreadsheet update value in SharedStringTableSharedStringTable 中的 OpenXML 电子表格更新值
【发布时间】: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];
                    }
                }
            }
        }

文档在这里http://msdn.microsoft.com/en-us/library/documentformat.openxml.openxmlcompositeelement.innertext(v=office.14).aspx

即使文档提到可以设置内部文本,但是没有设置访问器。 有谁知道如何设置InterText。由于我可能有许多具有相同变量名称“$$$abc”的单元格,我想将它们全部替换为“Payson”。

【问题讨论】:

    标签: c# excel openxml


    【解决方案1】:

    看来您需要替换 InnerXml,然后保存 SharedStringTable。见Set text value using SharedStringTable with xml sdk in .net

    【讨论】:

    【解决方案2】:

    我已经尝试编辑文本并且它有效。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多