Home » excel » excel – Set text value using SharedStringTable with xml sdk in .net

excel – Set text value using SharedStringTable with xml sdk in .net

Posted by: admin May 14, 2020 Leave a comment


I have a piece of code (below) that can get the text of an specific cell in excel, but I don’t know how to modify this text to change the cell text.

public static void UpdateTextCell(string docName, string text, uint rowIndex, 
    string columnName, string sheetName)
   // Open the document for editing.
   using (SpreadsheetDocument spreadSheet = SpreadsheetDocument
       .Open(docName, true))
        WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, 

        if (worksheetPart != null)

          SharedStringTablePart sharedstringtablepart=spreadSheet.WorkbookPart
          SharedStringTable sharedStringTable = sharedstringtablepart
          Cell cell = GetCell(worksheetPart.Worksheet, columnName, rowIndex);
          if (cell.DataType.Value == CellValues.SharedString)
             var value = cell.InnerText;
             value = sharedStringTable.ElementAt(int.Parse(value)).InnerText;
                 .Replace("value", "Modified");
          // Save the worksheet.

Since sharedStringTable.ElementAt(int.Parse(value)).InnerText is read only, I tried to modify the text string using sharedStringTable.ElementAt(int.Parse(value)).InnerXml.Replace("value", "Modified"); but this doesn’t work either.

Do you know what I’m missing?

How to&Answers:

Try adding



                 .Replace("value", "Modified");


Replace is a string function it just returns new string. All you need to do is set new value for InnerXml.

sharedStringTable.ElementAt(int.Parse(value)).InnerXml = sharedStringTable.ElementAt(int.Parse(value)).InnerXml
             .Replace("value", "Modified");


The solution with Replace bears a problem in case of text, which is also part of the xml, like a string containing only the letter ‘m’. Replace will then also replace the m in

< x:t xmlns:x= … >, rendering the cell invalid. Instead, replaceing the FirstChild, which is indeed the InnerText, bypasses restrictions of replacable text.

    new Text("Modified"),  // OpenXmlElement