c# - Open XML SDK:如何更新 Excel 单元格?
问题描述
我正在尝试通过 Open XML SDK 更新 Excel 电子表格中的单元格:
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 应用程序恢复之后:
环境:
- 文档格式.OpenXml:2.13.0
- Excel:Microsoft 265 MSO (16.0.14026.20270) 64 位
我做错了什么?
解决方案
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 会在加载时将您的内联字符串重写为共享字符串,如果您希望文件在保存前后不进行任何更改完全相同,请注意这一点。
推荐阅读
- matlab - 使用卡尔曼滤波器从加速度计和陀螺仪数据进行定位估计
- kubernetes - minikube 入口远程访问
- python - python - 如何在python中并行化多个计算时间非常长的for循环?
- floating-point - 浮点数:在归一化之前取整,反之亦然?
- python - Python如何传递命令行参数以正常运行
- python - django.db.utils.IntegrityError:唯一约束失败:new__main_doctor.email
- javascript - 根据电影类型随机化电影标题
- javascript - Css 样式在 React 中不起作用,将 Webpack 用于 css-loader
- kubernetes - Kubernetes 负载平衡/故障转移外部 MariaDB PXC 集群节点的方式
- javascript - 我的 Strapi 管理面板现在无限期地在 localhost 上显示加载状态