Skip to content

Commit 1d22a55

Browse files
Fix template calcChain regeneration and $= formula cells (MiniExcel.OpenXml) (#993)
* Fix template calcChain regeneration and $= formula cells (v2 / MiniExcel.OpenXml) Porting the v1.x template-render fixes to the v2 OpenXml line, where the engine moved to src/MiniExcel.OpenXml/ and a LINQ-to-XML rewrite. Two defects made Excel reject an otherwise-valid rendered package: - $= formula cells kept their source t="inlineStr" attribute after the inline string was replaced with an <f> child — a cell typed inlineStr with no <is> is schema-invalid. The attribute is now removed. - The regenerated calcChain entry took the cell address from the running child-index, which is wrong for sparse rows (cells with no content are not emitted, so position != column). The address is now read from the cell's own r attribute. - The template's own calcChain was reused/copied even though row insertion shifts every formula cell, leaving stale entries; and an empty calcChain (no rendered formulas) was written, which is schema-invalid. The chain is now regenerated only when formulas were rendered and dropped entirely otherwise — Excel rebuilds it on open. The <f> namespace fix from the v1 change is not needed here: v2's XElement-based serialization already emits it in the spreadsheetml namespace. * Removed obsolete FluentMapping folder from project * Converted usage of some raw strings to typed constants * Changed the ProcessFormulas method to calculate cell references based on the full "r" attribute when available * Added regression tests for new handling of calcChain data * Minor fix in the generation of the path/name map for the sheets * Removed ghost calcChain references across the generated package Added logic to remove calcChain references from [Content_Types].xml and workbook.xml.rels when the calcChain is not to be copied from the template's archive. * Fixed minor issue with the extrapolation of calcChain references --------- Co-authored-by: Michele Bastione <michele.bastione@gmail.com>
1 parent 5195330 commit 1d22a55

6 files changed

Lines changed: 292 additions & 59 deletions

File tree

‎src/MiniExcel.OpenXml/MiniExcel.OpenXml.csproj‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,4 @@
1818
<InternalsVisibleTo Include="MiniExcel.OpenXml.FluentMapping, PublicKey=002400000480000094000000060200000024000052534131000400000100010091c2c6c10d20b6c884dbc48892f91cc773d33c3a1f43ba3352700031d2d5f6a2b37cccd60469733a4597bdd94b54ee63f514dc487b21be797b1b63063941630b46ad090baabaf0650d05b9c590ea497644f0c296bb223e17dc785f0fbb255ef780905aabf4cf14ee5bca087cbd41d2231169a620529626035215604261b533c9"/>
1919
</ItemGroup>
2020

21-
<ItemGroup>
22-
<Folder Include="FluentMapping\" />
23-
</ItemGroup>
24-
2521
</Project>

‎src/MiniExcel.OpenXml/Templates/OpenXmlTemplate.Impl.cs‎

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -937,7 +937,16 @@ private void ProcessFormulas(StringBuilder rowXml, int rowIndex)
937937
str.AddBeforeSelf(fNode);
938938
str.Remove();
939939

940-
var celRef = CellReferenceConverter.GetCellFromCoordinates(index, rowIndex);
940+
// the cell no longer holds an inline string; keeping t="inlineStr" without the <is> tag is invalid
941+
cell.Attribute("t")?.Remove();
942+
943+
// take the column from the cell's own reference — the running index is wrong for
944+
// sparse rows (cells without content are not emitted, so position != column)
945+
var rAttr = cell.Attribute("r")?.Value;
946+
var celRef = string.IsNullOrEmpty(rAttr)
947+
? CellReferenceConverter.GetCellFromCoordinates(index, rowIndex)
948+
: rAttr;
949+
941950
_calcChainCellRefs.Add(celRef);
942951
}
943952
}
@@ -964,11 +973,11 @@ private void ProcessFormulas(StringBuilder rowXml, int rowIndex)
964973
private static StringBuilder CleanXml(StringBuilder xml, string? prefix = null)
965974
{
966975
var sb = xml
967-
.Replace("xmlns:x14ac=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\"", "")
968-
.Replace("xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"", "");
976+
.Replace($"xmlns:x14ac={Schemas.SpreadsheetmlXmlX14Ac}", "")
977+
.Replace($"xmlns={Schemas.SpreadsheetmlXmlMain}", "");
969978

970979
return !string.IsNullOrEmpty(prefix)
971-
? sb.Replace($"xmlns:{prefix}=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"", "")
980+
? sb.Replace($"xmlns:{prefix}={Schemas.SpreadsheetmlXmlMain}", "")
972981
: sb;
973982
}
974983

@@ -982,7 +991,7 @@ private static void InjectSharedStrings(IDictionary<int, string> sharedStrings,
982991
var t = cell.Attribute("t");
983992
var v = cell.Element(SpreadsheetNs + "v");
984993

985-
if (v?.Value is null || t?.Value != "s")
994+
if (v?.Value is null || t?.Value != ExcelDataTypes.SharedString)
986995
continue;
987996

988997
//needs to check if sharedstring exists or not
@@ -995,21 +1004,21 @@ private static void InjectSharedStrings(IDictionary<int, string> sharedStrings,
9951004
var tNode = new XElement(SpreadsheetNs + "t", shared);
9961005
var isNode = new XElement(SpreadsheetNs + "is", tNode);
9971006
cell.Add(isNode);
998-
cell.SetAttributeValue("t", "inlineStr");
1007+
cell.SetAttributeValue("t", ExcelDataTypes.InlineString);
9991008
}
10001009
}
10011010
}
10021011

10031012
private static void SetCellType(XElement cell, string type)
10041013
{
10051014
// Force inlineStr for strings
1006-
if (type == "str")
1007-
type = "inlineStr";
1015+
if (type == ExcelDataTypes.CalculatedString)
1016+
type = ExcelDataTypes.InlineString;
10081017

1009-
if (type == "inlineStr")
1018+
if (type == ExcelDataTypes.InlineString)
10101019
{
10111020
// Ensure <is><t>...</t></is>
1012-
cell.SetAttributeValue("t", "inlineStr");
1021+
cell.SetAttributeValue("t", ExcelDataTypes.InlineString);
10131022

10141023
if (cell.Element(SpreadsheetNs + "v") is { } v)
10151024
{
@@ -1020,7 +1029,7 @@ private static void SetCellType(XElement cell, string type)
10201029
var isNode = new XElement(SpreadsheetNs + "is", tNode);
10211030

10221031
cell.Add(isNode);
1023-
cell.SetAttributeValue("t", "inlineStr");
1032+
cell.SetAttributeValue("t", ExcelDataTypes.InlineString);
10241033
}
10251034
else if (cell.Element(SpreadsheetNs + "is") is null)
10261035
{
@@ -1036,8 +1045,8 @@ private static void SetCellType(XElement cell, string type)
10361045
// Ensure <v>...</v>
10371046
// For numbers/booleans, we remove 't' attribute to let it be default (number)
10381047
// or we could set it to 'n' explicitly, but removing is safer for general number types
1039-
if (type == "b")
1040-
cell.SetAttributeValue("t", "b");
1048+
if (type == ExcelDataTypes.Boolean)
1049+
cell.SetAttributeValue("t", ExcelDataTypes.Boolean);
10411050
else
10421051
cell.Attribute("t")?.Remove();
10431052

‎src/MiniExcel.OpenXml/Templates/OpenXmlTemplate.ValueExtractorHook.cs‎

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ static void TraverseAndFlatten(
169169
/// Adds worksheets to the workbook and register them int workbook.xml and workbook.xml.rels
170170
/// </summary>
171171
[CreateSyncVersion]
172-
private static async Task BatchAddSheetsToWorkbookAsync(ZipArchive outputZip, ZipArchive templateArchive, List<(int Index, string Name)> sheetInfos, CancellationToken cancellationToken)
172+
private static async Task BatchAddSheetsToWorkbookAsync(ZipArchive outputZip, ZipArchive templateArchive, List<(int Index, string Name)> sheetInfos, bool removeCalcChainFromRels, CancellationToken cancellationToken)
173173
{
174174
// Load the workbook and its relationships from the template
175175
var relDoc = await LoadXmlAsync(templateArchive, ExcelFileNames.WorkbookRels, cancellationToken).ConfigureAwait(false);
@@ -188,25 +188,34 @@ private static async Task BatchAddSheetsToWorkbookAsync(ZipArchive outputZip, Zi
188188
}
189189

190190
// 2. Clean up all relationship records pointing to worksheets in workbook.xml.rels
191-
var relsRoot = relDoc.Root;
192-
if (relsRoot != null)
191+
if (relDoc.Root is { } relsRoot)
193192
{
194-
// Only delete relationships of Type 'worksheet', preserving core relationships like sharedStrings/styles/theme
193+
// Remove the calcChain relationship if the contents have been invalidated upstream
194+
if (removeCalcChainFromRels)
195+
{
196+
var calcChainRecord = relsRoot.Elements().FirstOrDefault(x =>
197+
x.Attribute("Target")?.Value
198+
.EndsWith("calcChain.xml", StringComparison.OrdinalIgnoreCase) is true
199+
);
200+
calcChainRecord?.Remove();
201+
}
202+
203+
// Delete relationships of Type 'worksheet', preserving core relationships like sharedStrings/styles/theme
195204
var worksheetRels = relsRoot.Elements(PackageRelNs + "Relationship")
196205
.Where(r => r.Attribute("Type")?.Value == Schemas.SpreadsheetmlXmlWorksheetRelationship);
197206

198207
// Remove the filtered worksheet relationships
199208
foreach (var rel in worksheetRels)
200209
rel.Remove();
201-
}
202210

203-
// Batch add new relationship records for each generated sheet
204-
foreach (var sheet in sheetInfos)
205-
{
206-
relDoc.Root!.Add(new XElement(PackageRelNs + "Relationship",
207-
new XAttribute("Id", $"rIdSheet{sheet.Index}"),
208-
new XAttribute("Type", Schemas.SpreadsheetmlXmlWorksheetRelationship),
209-
new XAttribute("Target", $"worksheets/sheet{sheet.Index}.xml")));
211+
// Batch add new relationship records for each generated sheet
212+
foreach (var sheet in sheetInfos)
213+
{
214+
relsRoot.Add(new XElement(PackageRelNs + "Relationship",
215+
new XAttribute("Id", $"rIdSheet{sheet.Index}"),
216+
new XAttribute("Type", Schemas.SpreadsheetmlXmlWorksheetRelationship),
217+
new XAttribute("Target", $"worksheets/sheet{sheet.Index}.xml")));
218+
}
210219
}
211220

212221
// Batch add new sheet definitions to the workbook
@@ -245,10 +254,11 @@ private async Task<Dictionary<string, string>> GetSheetNameMapAsync(ZipArchive a
245254
if (rel.Attribute("Id")?.Value is { } rid)
246255
{
247256
var target = rel.Attribute("Target")?.Value;
248-
if (string.IsNullOrEmpty(rid) || string.IsNullOrEmpty(target)) continue;
257+
if (string.IsNullOrEmpty(rid) || string.IsNullOrEmpty(target))
258+
continue;
249259

250260
// Construct the full internal path (ensure forward slashes for consistency)
251-
var fullSheetPath = Path.Combine("xl", target).Replace("\\", "/");
261+
var fullSheetPath = Path.Combine("xl", target).Replace("\\", "/").TrimStart('/');
252262
ridToSheetPath[rid] = fullSheetPath;
253263
}
254264
}

‎src/MiniExcel.OpenXml/Templates/OpenXmlTemplate.cs‎

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ public async Task SaveAsByTemplateAsync(Stream templateStream, object value, Can
8787
var entryName = entry.FullName.TrimStart('/');
8888
if (entryName.StartsWith(ExcelFileNames.WorksheetBase, StringComparison.OrdinalIgnoreCase) ||
8989
entryName.Equals(ExcelFileNames.CalcChain, StringComparison.OrdinalIgnoreCase) ||
90+
entryName.Equals(ExcelFileNames.ContentTypes, StringComparison.OrdinalIgnoreCase) ||
9091
entryName.Equals(ExcelFileNames.Workbook, StringComparison.OrdinalIgnoreCase) ||
9192
entryName.Equals(ExcelFileNames.WorkbookRels, StringComparison.OrdinalIgnoreCase))
9293
{
@@ -124,7 +125,7 @@ await originalEntryStream.CopyToAsync(newEntryStream
124125

125126
foreach (var templateSheet in templateSheets)
126127
{
127-
// XRowInfos musy be cleared for every sheet or it'll cause duplicates: https://user-images.githubusercontent.com/12729184/115003101-0fcab700-9ed8-11eb-9151-ca4d7b86d59e.png
128+
// XRowInfos must be cleared for every sheet or it'll cause duplicates: https://user-images.githubusercontent.com/12729184/115003101-0fcab700-9ed8-11eb-9151-ca4d7b86d59e.png
128129
_xRowInfos.Clear();
129130
_xMergeCellInfos.Clear();
130131
_newXMergeCellInfos.Clear();
@@ -155,44 +156,40 @@ await originalEntryStream.CopyToAsync(newEntryStream
155156
}
156157
}
157158

158-
// batch add sheet
159-
await BatchAddSheetsToWorkbookAsync(outputFileArchive.ZipFile, originalArchive, allSheetInfos, cancellationToken).ConfigureAwait(false);
160-
161-
// create mode we need to not create first then create here
162-
var calcChain = outputFileArchive.EntryCollection.FirstOrDefault(e
159+
// The template's own calcChain cannot be reused: row insertion shifts formula cells and its
160+
// entries would point at the old addresses. It is regenerated from the rendered formulas —
161+
// and when none were rendered, dropped entirely, because a calcChain with no <c> entries is
162+
// schema-invalid and Excel rejects the whole package either way.
163+
// Excel rebuilds the chain on open, so dropping it is always safe.
164+
var calcChain = outputFileArchive.EntryCollection.FirstOrDefault(e
163165
=> e.FullName.TrimStart('/').Equals(ExcelFileNames.CalcChain, StringComparison.OrdinalIgnoreCase));
164166

165-
if (calcChain is not null)
167+
var contentTypesDoc = await LoadXmlAsync(originalArchive, ExcelFileNames.ContentTypes, cancellationToken).ConfigureAwait(false);
168+
var isValidCalcChain = calcChain is not null && _calcChainContent.Length > 0;
169+
170+
if (isValidCalcChain)
166171
{
167-
var calcChainEntry = outputFileArchive.ZipFile.CreateEntry(calcChain.FullName);
172+
var calcChainEntry = outputFileArchive.ZipFile.CreateEntry(calcChain!.FullName);
168173
var calcChainStream = await calcChainEntry.OpenAsync(cancellationToken).ConfigureAwait(false);
169174
await using var disposableChainEntryStream = calcChainStream.ConfigureAwait(false);
170175

171176
await CalcChainHelper.GenerateCalcChainSheetAsync(calcChainStream, _calcChainContent.ToString(), cancellationToken).ConfigureAwait(false);
172177
}
173178
else
174179
{
175-
foreach (var entry in originalArchive.Entries)
176-
{
177-
if (entry.FullName.TrimStart('/').Equals(ExcelFileNames.CalcChain, StringComparison.OrdinalIgnoreCase))
178-
{
179-
var newEntry = outputFileArchive.ZipFile.CreateEntry(entry.FullName);
180-
181-
// Copy the content of the original entry to the new entry
182-
var originalEntryStream = await entry.OpenAsync(cancellationToken).ConfigureAwait(false);
183-
await using var disposableEntryStream = originalEntryStream.ConfigureAwait(false);
184-
185-
var newEntryStream = await newEntry.OpenAsync(cancellationToken).ConfigureAwait(false);
186-
await using var disposableNewEntryStream = newEntryStream.ConfigureAwait(false);
187-
188-
await originalEntryStream.CopyToAsync(newEntryStream
189-
#if NET
190-
, cancellationToken
191-
#endif
192-
).ConfigureAwait(false);
193-
}
194-
}
180+
var elements = contentTypesDoc.Root?.Elements();
181+
var calcChainRecord = elements?.FirstOrDefault(x =>
182+
x.Attribute("PartName")?.Value.TrimStart('/')
183+
.Equals(ExcelFileNames.CalcChain, StringComparison.OrdinalIgnoreCase) is true
184+
);
185+
calcChainRecord?.Remove();
195186
}
187+
188+
// saving the (possibly edited) [Content_Types].xml entry
189+
await SaveXmlToZipAsync(outputFileArchive.ZipFile, ExcelFileNames.ContentTypes, contentTypesDoc, cancellationToken).ConfigureAwait(false);
190+
191+
// editing the workbook and its rels to reflect the new worksheets' metadata
192+
await BatchAddSheetsToWorkbookAsync(outputFileArchive.ZipFile, originalArchive, allSheetInfos, !isValidCalcChain, cancellationToken).ConfigureAwait(false);
196193

197194
#if NET10_0_OR_GREATER
198195
await outputFileArchive.ZipFile.DisposeAsync().ConfigureAwait(false);
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
using System.Xml.Linq;
2+
using ClosedXML.Excel;
3+
using MiniExcelLib.OpenXml.Constants;
4+
using MiniExcelLib.Tests.Common.Utils;
5+
6+
namespace MiniExcelLib.OpenXml.Tests.Templates;
7+
8+
public class CalcChainAsyncTests
9+
{
10+
private readonly OpenXmlTemplater _templater = MiniExcel.Templaters.GetOpenXmlTemplater();
11+
12+
[Fact]
13+
public async Task TemplateWithStaticFormula_DoesNotWriteStaleOrEmptyCalcChain()
14+
{
15+
// A template with a static Excel formula (below an IEnumerable row) carries a calcChain
16+
// pointing at the formula's pre-render address. After rows are inserted the address is
17+
// stale — the rendered package must not contain a stale or empty calcChain.
18+
using var template = AutoDeletingPath.Create();
19+
using (var wb = new XLWorkbook())
20+
{
21+
var ws = wb.AddWorksheet("Sheet1");
22+
ws.Cell("A1").Value = "{{title}}";
23+
ws.Cell("A3").Value = "{{items.Name}}";
24+
ws.Cell("B3").Value = "{{items.Qty}}";
25+
ws.Cell("B5").FormulaA1 = "SUM(B3:B4)";
26+
wb.SaveAs(template.FilePath);
27+
}
28+
29+
using var path = AutoDeletingPath.Create();
30+
Dictionary<string, object?> data = new()
31+
{
32+
["title"] = "FooCompany",
33+
["items"] = new[]
34+
{
35+
new { Name = "A", Qty = 1 },
36+
new { Name = "B", Qty = 2 },
37+
}
38+
};
39+
await _templater.FillTemplateAsync(path.ToString(), template.FilePath, data);
40+
41+
using var zip = ZipFile.OpenRead(path.ToString());
42+
var calcChain = zip.GetEntry("xl/calcChain.xml");
43+
if (calcChain != null)
44+
{
45+
using var reader = new StreamReader(calcChain.Open());
46+
var content = await reader.ReadToEndAsync();
47+
Assert.Contains("<c ", content); // an empty calcChain is schema-invalid
48+
Assert.DoesNotContain(@"r=""B5""", content); // the pre-render address is stale after the row shift
49+
}
50+
}
51+
52+
[Fact]
53+
public async Task DollarFormulaInSparseRow_WritesValidFormulaCellAndCorrectCalcChainRef()
54+
{
55+
// The '$=' formula sits in column D of a row whose only other cell is in column A, so the
56+
// formula cell's child-list position (1) differs from its column (D) — the calcChain ref
57+
// must come from the cell's own address. The rendered cell must be a real formula element
58+
// in the spreadsheetml namespace, not an inline string.
59+
using var template = AutoDeletingPath.Create();
60+
using (var wb = new XLWorkbook())
61+
{
62+
var ws = wb.AddWorksheet("Sheet1");
63+
// the static formula makes the authoring library emit a calcChain part, so the
64+
// regeneration path runs; without one the template carries no chain to regenerate
65+
ws.Cell("F1").FormulaA1 = "1+1";
66+
ws.Cell("A5").Value = "{{items.Name}}";
67+
ws.Cell("B5").Value = "{{items.Qty}}";
68+
ws.Cell("A7").Value = "Total";
69+
ws.Cell("D7").Value = "$=SUM(B{{$enumrowstart}}:B{{$enumrowend}})";
70+
wb.SaveAs(template.FilePath);
71+
}
72+
73+
using var path = AutoDeletingPath.Create();
74+
Dictionary<string, object?> data = new()
75+
{
76+
["title"] = "FooCompany",
77+
["items"] = new[]
78+
{
79+
new { Name = "A", Qty = 1 },
80+
new { Name = "B", Qty = 2 },
81+
}
82+
};
83+
await _templater.FillTemplateAsync(path.ToString(), template.FilePath, data);
84+
85+
using var zip = ZipFile.OpenRead(path.ToString());
86+
87+
// the formula cell: <c r="D8"> (two items shift row 7 to 8) with a namespaced <f> child and no inlineStr type
88+
XDocument doc;
89+
await using (var sheet = zip.GetEntry("xl/worksheets/sheet1.xml")!.Open())
90+
{
91+
doc = await XDocument.LoadAsync(sheet, System.Xml.Linq.LoadOptions.None, CancellationToken.None);
92+
}
93+
94+
var ns = (XNamespace)Schemas.SpreadsheetmlXmlMain;
95+
var formulaCell = doc.Descendants(ns + "c").FirstOrDefault(x => x.Attribute("r")?.Value == "D8");
96+
Assert.NotNull(formulaCell);
97+
Assert.Equal("SUM(B5:B6)", formulaCell.Element(ns + "f")?.Value);
98+
Assert.NotEqual("inlineStr", formulaCell.Attribute("t")?.Value);
99+
100+
// the regenerated calcChain points at the formula's real address, not the one derived
101+
// from the cell's position in the row (which would be column B here)
102+
using var chainReader = new StreamReader(zip.GetEntry("xl/calcChain.xml")!.Open());
103+
var chain = await chainReader.ReadToEndAsync();
104+
Assert.Contains(@"r=""D8""", chain);
105+
Assert.DoesNotContain(@"r=""B8""", chain);
106+
}
107+
}

0 commit comments

Comments
 (0)