Set text value using SharedStringTable with xml sdk in .net

南楼画角 提交于 2019-12-11 04:48:17

问题


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?


回答1:


Try adding

sharedStringTable.Save();

after

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/11061551/set-text-value-using-sharedstringtable-with-xml-sdk-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!