Skip to content

Commit 7ed3376

Browse files
committed
fix: four value errors found against other readers' corpora
- A 1904 workbook kept its epoch only until Excel's <x15:workbookPr> extension element, whose local name is the same, reset it: every date four years and a day early. - Serial dates are rounded to the millisecond instead of truncated, so 16:00 no longer reads as 15:59:59.999. - The East Asian built-in date formats (27-36, 50-58) are read as dates. - The <rPh> phonetic guide is left out of shared and inline strings instead of being appended to the text it annotates (#8).
1 parent 8eb6890 commit 7ed3376

4 files changed

Lines changed: 159 additions & 21 deletions

File tree

‎docs/KNOWN-ISSUES.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,6 @@ Reviewed 2026-08-26, before the library moved to its own repository.
1717

1818
## Correctness at the edges
1919

20-
### The `<rPh>` phonetic guide is concatenated into the value
21-
Both the shared-string and inline-string paths append every `<t>` descendant, and per ECMA-376
22-
§18.4.6 the text inside `<rPh>` is a rendering aid, not the cell's value. A Japanese workbook where a
23-
name carries a reading yields the name with its reading appended to it, instead of the name.
24-
25-
**Matters when** a customer uploads a file produced by a Japanese Excel. Fix by skipping the `<rPh>`
26-
and `<phoneticPr>` subtrees.
27-
2820
### A `numFmt` inside `<dxfs>` can overwrite a cell format
2921
Number formats are collected from anywhere in `styles.xml`. Differential formats — used by
3022
conditional formatting — live in `<dxfs>` and carry their own ids. One colliding with a custom id

‎src/TriasDev.Tabular/Xlsx/XlsxCursor.cs‎

Lines changed: 59 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ public sealed class XlsxCursor : ITabularCursor
4848
private const string StrictRelationshipNamespace =
4949
"http://purl.oclc.org/ooxml/officeDocument/relationships";
5050

51+
/// <summary>SpreadsheetML's own namespace, transitional and strict — identifiers, never fetched.</summary>
52+
private const string SpreadsheetNamespace = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
53+
54+
private const string StrictSpreadsheetNamespace = "http://purl.oclc.org/ooxml/spreadsheetml/main";
55+
5156
private readonly ZipArchive _package;
5257

5358
/// <summary>
@@ -212,6 +217,10 @@ private static string Resolve(string folder, string target)
212217
private static string? PathOfType(Dictionary<string, Relationship> relationships, string typeSuffix) =>
213218
relationships.Values.FirstOrDefault(r => r.Type.EndsWith(typeSuffix, StringComparison.Ordinal)).Path;
214219

220+
/// <summary>Whether a namespace is SpreadsheetML's own, transitional or strict.</summary>
221+
private static bool IsSpreadsheetNamespace(string uri) =>
222+
uri is SpreadsheetNamespace or StrictSpreadsheetNamespace;
223+
215224
/// <summary>One relationship: its type, and the part it points at, resolved.</summary>
216225
private readonly record struct Relationship(string Type, string Path);
217226

@@ -522,6 +531,7 @@ private string ReadInlineString(SheetScanner scanner, CancellationToken cancella
522531

523532
_inlineText.Clear();
524533
bool inText = false;
534+
bool inPhonetic = false; // inside <rPh>, whose text is a reading aid, not the value
525535
int sinceCheck = 0;
526536

527537
while (scanner.Read())
@@ -541,10 +551,12 @@ private string ReadInlineString(SheetScanner scanner, CancellationToken cancella
541551

542552
case XmlNodeKind.EndElement:
543553
inText &= !scanner.Name.SequenceEqual("t");
554+
inPhonetic &= !scanner.Name.SequenceEqual("rPh");
544555
break;
545556

546557
case XmlNodeKind.Element:
547-
inText = scanner.Name.SequenceEqual("t") && !scanner.IsEmptyElement;
558+
inPhonetic |= scanner.Name.SequenceEqual("rPh") && !scanner.IsEmptyElement;
559+
inText = !inPhonetic && scanner.Name.SequenceEqual("t") && !scanner.IsEmptyElement;
548560
break;
549561

550562
case XmlNodeKind.Text when inText:
@@ -765,25 +777,50 @@ private static string ReadSharedStringItem(
765777
break;
766778
}
767779

768-
advance = true;
769-
770780
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "si")
771781
{
772782
break;
773783
}
774784

775-
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t")
776-
{
785+
advance = reader.NodeType != XmlNodeType.Element
786+
|| ReadItemElement(reader, text, chunk, maxChars, cancellationToken);
787+
}
788+
789+
return text.ToString();
790+
}
791+
792+
/// <summary>
793+
/// Takes what one element inside <c>&lt;si&gt;</c> contributes, and says whether the loop should
794+
/// advance past where it leaves the reader.
795+
/// </summary>
796+
private static bool ReadItemElement(
797+
XmlReader reader,
798+
StringBuilder text,
799+
char[] chunk,
800+
int maxChars,
801+
CancellationToken cancellationToken)
802+
{
803+
switch (reader.LocalName)
804+
{
805+
case "rPh":
806+
// The phonetic guide — furigana over Japanese text — is a rendering aid, not part of
807+
// the value; its <t> would otherwise be appended to the text it annotates. Skip
808+
// leaves the reader on the node after it, which the loop must look at.
809+
reader.Skip();
810+
return false;
811+
812+
case "t":
777813
// AppendText leaves the reader on the node after the element's content, which the
778814
// loop must look at rather than skip. An empty <t/> has no content: the reader has
779815
// not moved, and not advancing past it read the same element forever — any workbook
780816
// holding an empty shared string hung its first read.
781-
advance = reader.IsEmptyElement;
817+
bool empty = reader.IsEmptyElement;
782818
AppendText(reader, text, chunk, maxChars, cancellationToken);
783-
}
784-
}
819+
return empty;
785820

786-
return text.ToString();
821+
default:
822+
return true;
823+
}
787824
}
788825

789826
/// <summary>
@@ -922,7 +959,10 @@ private Dictionary<string, Relationship> ReadRelationships(
922959
continue;
923960
}
924961

925-
if (reader.LocalName == "workbookPr")
962+
// The workbook's own properties, not an extension's: Excel 2013 and later also write
963+
// <x15:workbookPr chartTrackingRefBase="1"/>, and reading that one as well reset a
964+
// 1904 workbook to the 1900 epoch — every date four years and a day early.
965+
if (reader.LocalName == "workbookPr" && IsSpreadsheetNamespace(reader.NamespaceURI))
926966
{
927967
string? value = reader.GetAttribute("date1904");
928968
date1904 = value is "1" or "true";
@@ -1123,8 +1163,12 @@ private static bool[] FlattenDateStyles(List<int> cellFormats, Dictionary<int, s
11231163
}
11241164

11251165
/// <summary>The number format identifiers the specification reserves for dates and times.</summary>
1166+
/// <remarks>
1167+
/// 14–22 and 45–47 everywhere, and 27–36 and 50–58 for the East Asian locales, which a workbook
1168+
/// saved by a Japanese, Chinese or Korean Excel uses without declaring a format code.
1169+
/// </remarks>
11261170
private static bool IsBuiltInDateFormat(int numFmtId) =>
1127-
numFmtId is (>= 14 and <= 22) or (>= 45 and <= 47);
1171+
numFmtId is (>= 14 and <= 22) or (>= 27 and <= 36) or (>= 45 and <= 47) or (>= 50 and <= 58);
11281172

11291173
/// <summary>
11301174
/// Decides whether a custom format code renders a date, by looking for date tokens outside the
@@ -1223,7 +1267,10 @@ private static bool TryFromSerial(double serial, bool date1904, out DateTime dat
12231267
days = serial;
12241268
}
12251269

1226-
double ticks = days * TimeSpan.TicksPerDay;
1270+
// Rounded to the millisecond, which is all a serial date carries. The fraction for 16:00 is
1271+
// stored a hair below its true value, and truncating the ticks read it as 15:59:59.999.
1272+
double ticks = Math.Round(days * TimeSpan.TicksPerDay / TimeSpan.TicksPerMillisecond)
1273+
* TimeSpan.TicksPerMillisecond;
12271274

12281275
if (ticks < (DateTime.MinValue - epoch).Ticks || ticks > (DateTime.MaxValue - epoch).Ticks)
12291276
{

‎tests/TriasDev.Tabular.Tests/Fixtures/XlsxPackage.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ internal sealed class XlsxPackage
2323
private string _folder = "xl/";
2424
private Func<int, string> _sheetPart = number => $"worksheets/sheet{number}.xml";
2525
private string _extraSheetsXml = string.Empty;
26+
private string _workbookTailXml = string.Empty;
2627
private string _relationshipNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
2728

2829
/// <summary>Adds a worksheet whose <c>&lt;sheetData&gt;</c> children are supplied verbatim.</summary>
@@ -83,6 +84,13 @@ public XlsxPackage WithSheetPartNames(Func<int, string> name)
8384
return this;
8485
}
8586

87+
/// <summary>Appends raw markup to the workbook part after its sheet list — an extension list, say.</summary>
88+
public XlsxPackage WithWorkbookTail(string xml)
89+
{
90+
_workbookTailXml = xml;
91+
return this;
92+
}
93+
8694
/// <summary>Declares the workbook's <c>r:id</c> attributes in the strict variant's namespace.</summary>
8795
public XlsxPackage WithStrictRelationshipNamespace()
8896
{
@@ -189,7 +197,9 @@ private string Workbook()
189197
sb.Append($"""<sheet name="{Escape(_sheets[i].Name)}" sheetId="{i + 1}" r:id="rId{i + 1}"/>""");
190198
}
191199
sb.Append(_extraSheetsXml);
192-
sb.Append("</sheets></workbook>");
200+
sb.Append("</sheets>");
201+
sb.Append(_workbookTailXml);
202+
sb.Append("</workbook>");
193203
return sb.ToString();
194204
}
195205

‎tests/TriasDev.Tabular.Tests/Xlsx/ProducerQuirksTests.cs‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using TriasDev.Tabular.Abstractions;
12
using TriasDev.Tabular.Tests.Fixtures;
23
using TriasDev.Tabular.Xlsx;
34

@@ -162,4 +163,92 @@ public void FollowsSheetRelationshipsDeclaredInTheStrictNamespace()
162163
Assert.True(cursor.ReadRow(TestContext.Current.CancellationToken));
163164
Assert.Equal("second", cursor.CurrentRow[0].AsText());
164165
}
166+
167+
/// <summary>A stylesheet whose second cell format is the given number format.</summary>
168+
private static string StylesWithFormat(int numFmtId) =>
169+
$"""<?xml version="1.0"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><cellXfs count="2"><xf numFmtId="0"/><xf numFmtId="{numFmtId}" applyNumberFormat="1"/></cellXfs></styleSheet>""";
170+
171+
private static RawCellSummary ReadFirstCell(byte[] content)
172+
{
173+
using MemoryStream stream = new(content, writable: false);
174+
using XlsxCursor cursor = new(stream);
175+
176+
Assert.True(cursor.ReadRow(TestContext.Current.CancellationToken));
177+
178+
RawCell cell = cursor.CurrentRow[0];
179+
return new RawCellSummary(cell.Kind, cell.Kind == RawCellKind.Date ? cell.Date : null, cell.AsText());
180+
}
181+
182+
private readonly record struct RawCellSummary(RawCellKind Kind, DateTime? Date, string? Text);
183+
184+
[Fact]
185+
public void KeepsThe1904EpochWhenAnExtensionElementSharesItsName()
186+
{
187+
// Excel 2013 and later add <x15:workbookPr chartTrackingRefBase="1"/> in an extension list.
188+
// Its local name is the same, and reading it as the workbook's own properties reset the epoch
189+
// to 1900: every date in a 1904 workbook came out four years and a day early.
190+
byte[] content = new XlsxPackage()
191+
.WithDate1904()
192+
.WithWorkbookTail("""<extLst><ext uri="{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"><x15:workbookPr chartTrackingRefBase="1"/></ext></extLst>""")
193+
.WithStyles(StylesWithFormat(14))
194+
.WithSheet("Sheet1", """<row r="1"><c r="A1" s="1"><v>43708</v></c></row>""")
195+
.Build();
196+
197+
Assert.Equal(new DateTime(2023, 9, 1, 0, 0, 0, DateTimeKind.Unspecified), ReadFirstCell(content).Date);
198+
}
199+
200+
[Fact]
201+
public void RoundsASerialDateToTheMillisecondExcelKeeps()
202+
{
203+
// 16:00 exactly is stored as 41655.666666666664, a hair below the true fraction. Truncating
204+
// the ticks read it as 15:59:59.999, which every other reader and Excel itself show as 16:00.
205+
byte[] content = new XlsxPackage()
206+
.WithStyles(StylesWithFormat(22))
207+
.WithSheet("Sheet1", """<row r="1"><c r="A1" s="1"><v>41655.666666666664</v></c></row>""")
208+
.Build();
209+
210+
Assert.Equal(new DateTime(2014, 1, 16, 16, 0, 0, DateTimeKind.Unspecified), ReadFirstCell(content).Date);
211+
}
212+
213+
[Theory]
214+
[InlineData(27)]
215+
[InlineData(31)]
216+
[InlineData(36)]
217+
[InlineData(50)]
218+
[InlineData(55)]
219+
[InlineData(58)]
220+
public void ReadsTheEastAsianBuiltInDateFormatsAsDates(int numFmtId)
221+
{
222+
// The specification reserves 27–36 and 50–58 for dates in East Asian locales; a workbook
223+
// saved by a Japanese, Chinese or Korean Excel uses them without declaring a format code.
224+
byte[] content = new XlsxPackage()
225+
.WithStyles(StylesWithFormat(numFmtId))
226+
.WithSheet("Sheet1", """<row r="1"><c r="A1" s="1"><v>44211</v></c></row>""")
227+
.Build();
228+
229+
Assert.Equal(new DateTime(2021, 1, 15, 0, 0, 0, DateTimeKind.Unspecified), ReadFirstCell(content).Date);
230+
}
231+
232+
[Fact]
233+
public void LeavesThePhoneticGuideOutOfASharedString()
234+
{
235+
// <rPh> carries the reading of the text above it — furigana — as a rendering aid, not as
236+
// part of the value. Concatenating it turned 漢字 into 漢字かんじ.
237+
byte[] content = new XlsxPackage()
238+
.WithSharedStrings("""<si><t>漢字</t><rPh sb="0" eb="2"><t>かんじ</t></rPh><phoneticPr fontId="1"/></si>""")
239+
.WithSheet("Sheet1", """<row r="1"><c r="A1" t="s"><v>0</v></c></row>""")
240+
.Build();
241+
242+
Assert.Equal("漢字", ReadFirstCell(content).Text);
243+
}
244+
245+
[Fact]
246+
public void LeavesThePhoneticGuideOutOfAnInlineString()
247+
{
248+
byte[] content = new XlsxPackage()
249+
.WithSheet("Sheet1", """<row r="1"><c r="A1" t="inlineStr"><is><t>漢字</t><rPh sb="0" eb="2"><t>かんじ</t></rPh></is></c></row>""")
250+
.Build();
251+
252+
Assert.Equal("漢字", ReadFirstCell(content).Text);
253+
}
165254
}

0 commit comments

Comments
 (0)