3

我有一段代码(如下)可以在excel中获取特定单元格的文本,但我不知道如何修改此文本以更改单元格文本。

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

由于sharedStringTable.ElementAt(int.Parse(value)).InnerText是只读的,我尝试使用修改文本字符串,sharedStringTable.ElementAt(int.Parse(value)).InnerXml.Replace("value", "Modified");但这也不起作用。

你知道我错过了什么吗?

4

3 回答 3

2

尝试添加

sharedStringTable.Save();

sharedStringTable.ElementAt(int.Parse(value)).InnerXml
                 .Replace("value", "Modified");
于 2012-06-18T10:21:02.907 回答
2

Replace 是一个字符串函数,它只返回新字符串。您需要做的就是为 InnerXml 设置新值。

sharedStringTable.ElementAt(int.Parse(value)).InnerXml = sharedStringTable.ElementAt(int.Parse(value)).InnerXml
             .Replace("value", "Modified");
于 2013-04-18T08:00:59.383 回答
0

Replace 的解决方案在文本的情况下存在问题,它也是 xml 的一部分,例如仅包含字母“m”的字符串。然后替换也将替换 m in

< x:t xmlns:x= ... >,使单元格无效。相反,替换确实是 InnerText 的 FirstChild 绕过了可替换文本的限制。

sharedStringTable.ElementAt(int.Parse(cell.CellValue.Text)).ReplaceChild(
    new Text("Modified"),  // OpenXmlElement 
    sharedStringTable.ElementAt(int.Parse(cell.CellValue.Text)).FirstChild
);
于 2018-06-14T12:18:37.253 回答