I am trying to update a cell in Excel's spreadsheet via Open XML SDK:
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();
}
}
}
That updates cell, but only after recovering by Excel app:
Environment:
What I do wrong?
Excel prefers to use SharedStrings instead of inline strings.
If the Cell.DataType == EnumValue<CellValues>(CellValues.SharedString)
you can't replace the CellValue without also adding a SharedString.
The easiest way to fix this is to switch the DataType to inline string, aka: CellValues.String and then assign the string value:
cell.DataType = new EnumValue<CellValues>(CellValues.String);
cell.CellValue = new CellValue("new");
Do note that Excel will rewrite your inline string to shared strings on load which is something to be aware of in case you expect the file before and after saving without making any changes to be exactly the same.