c# - 打开 XML SDK : How to update Excel cell?

标签 c# excel openxml spreadsheet openxml-sdk

我正在尝试通过 Open XML SDK 更新 Excel 电子表格中的单元格:

test.xlsx

enter image description here

using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace DotNetSandbox.SO
{
    public class CellUpdating
    {
        public static void Update()
        {
            using SpreadsheetDocument doc = SpreadsheetDocument.Open(@"c:\temp\test.xlsx", true);
            Sheet sheet = doc.WorkbookPart.Workbook.Descendants<Sheet>().First();
            WorksheetPart wsPart = (WorksheetPart)doc.WorkbookPart.GetPartById(sheet.Id);
            Cell cell = wsPart.Worksheet.Descendants<Cell>().First(c => c.CellReference == "A2");

            cell.CellValue = new CellValue("new");

            wsPart.Worksheet.Save();
        }
    }
}

更新单元格,但仅在通过 Excel 应用程序恢复之后:

enter image description here

环境:

  • DocumentFormat.OpenXml: 2.13.0
  • Excel:Microsoft 265 MSO (16.0.14026.20270) 64 位

我做错了什么?

最佳答案

Excel 更喜欢使用 SharedStrings 而不是内联字符串。

如果Cell.DataType == EnumValue<CellValues>(CellValues.SharedString)您不能在不添加 SharedString 的情况下替换 CellValue。

解决此问题的最简单方法是将数据类型切换为内联字符串,又名:CellValues.String,然后分配字符串值:

    cell.DataType = new EnumValue<CellValues>(CellValues.String); 
    cell.CellValue = new CellValue("new");

请注意,Excel 会在加载时将内联字符串重写为共享字符串,这一点需要注意,以防您希望文件在保存前后不做任何更改而完全相同。

关于c# - 打开 XML SDK : How to update Excel cell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68618458/

相关文章:

c# - 在 WPF 中创建自定义安装程序

vba - 在VBA中打印平面文件中不带引号的字符串

guid - DOCX(Open XML WordprocessingDocument)中唯一 ID 的最佳位置

excel - 将嵌入的 OLE 对象(Excel 工作簿)保存到 Excel 2010 中的文件

openxml - 打开 Xml - 文件需要修复才能打开

c# - 如何使用 OpenXML 删除项目符号和段落之间的空白内容

c# - 定时器类在程序结束前不触发

c# - 在委托(delegate)上使用 += 运算符不好吗?

c# - 多个结果集与多个性能调用

excel - 如何复制并粘贴最后一行直到某个日期?