I have a cell that contains the placeholder \"$$value\" in the Excel sheet, the thing is that I need to replace the placeholder\'s actual value using Open XML and save it as
Solution:
private static void ProcessTemplate(Stream template, Dictionary toReplace)
{
using (var workbook = SpreadsheetDocument.Open(template, true, new OpenSettings { AutoSave = true }))
{
workbook.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
workbook.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
//Replace SheetNames
foreach (Sheet sheet in workbook.WorkbookPart.Workbook.Sheets)
foreach (var key in toReplace.Keys)
sheet.Name.Value = sheet.Name.Value.Replace(key, toReplace[key]);
foreach (WorksheetPart wsheetpart in workbook.WorkbookPart.WorksheetParts)
foreach (SheetData sheetd in wsheetpart.Worksheet.Descendants())
foreach (Row r in wsheetpart.Worksheet.Descendants())
foreach (Cell c in r.Descendants())
if (c.CellFormula != null)
{
foreach (var key in toReplace.Keys)
c.CellFormula.Text = c.CellFormula.Text.Replace(key, toReplace[key]);
}
// Replace shared strings
SharedStringTablePart sharedStringsPart = workbook.WorkbookPart.SharedStringTablePart;
IEnumerable sharedStringTextElements = sharedStringsPart.SharedStringTable.Descendants();
for(int i =0;i sharedStringTextElementsF = sharedStringsPart.SharedStringTable.Descendants();
for (int i = 0; i < toReplace.Keys.Count; i++)
DoReplaceFormula(sharedStringTextElementsF, toReplace);
// Replace inline strings
IEnumerable worksheetParts = workbook.GetPartsOfType();
foreach (var worksheet in worksheetParts)
{
var allTextElements = worksheet.Worksheet.Descendants();
DoReplace(allTextElements, toReplace);
var allTextElements2 = worksheet.Worksheet.Descendants();
DoReplaceFormula(allTextElements2, toReplace);
}
} // AutoSave enabled
}