Search code examples
excelvstoopenxml-sdkvba

Set text value using SharedStringTable with xml sdk in .net


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, 
            sheetName);

        if (worksheetPart != null)
        {

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

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?


Solution

  • Try adding

    sharedStringTable.Save();
    

    after

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