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

Questions:

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?

How to&Answers:

Try adding

sharedStringTable.Save();

after

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

Answer:

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");

Answer:

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.

sharedStringTable.ElementAt(int.Parse(cell.CellValue.Text)).ReplaceChild(
    new Text("Modified"),  // OpenXmlElement 
    sharedStringTable.ElementAt(int.Parse(cell.CellValue.Text)).FirstChild
);