gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:08:51 28 4
gpt4 key购买 nike

我正在尝试通过 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com