Open XML SDK:如何更新Excel单元格?

4

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

test.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应用程序恢复后才生效:

enter image description here

环境:

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

我做错了什么?


我认为缺乏样式可能会成为一个问题。 - Dzmitry Tserakhau
你是指 cell.DataType = new EnumValue<CellValues>(CellValues.SharedString) 吗?但这样做也不行。 - Adam Shakhabov
1个回答

3

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

如果Cell.DataType == EnumValue<CellValues>(CellValues.SharedString),则无法替换CellValue而不添加SharedString。

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接