首页 > 解决方案 > Open XML SDK:如何更新 Excel 单元格?

问题描述

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

测试.xlsx

在此处输入图像描述

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 应用程序恢复之后:

在此处输入图像描述

环境:

我做错了什么?

标签: c#excelopenxmlspreadsheetopenxml-sdk

解决方案


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

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

解决此问题的最简单方法是将 DataType 切换为内联字符串,即 CellValues.String,然后分配字符串值:

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

请注意,Excel 会在加载时将您的内联字符串重写为共享字符串,如果您希望文件在保存前后不进行任何更改完全相同,请注意这一点。


推荐阅读