Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 0 additions & 13 deletions docs/KNOWN-ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,6 @@ the delimiter test is off, and only the 100-line bound catches a stray quote.
field boundary within one record. Neither the real-world nor the synthetic 5M-row fixture has such a
case.

### A `numFmt` inside `<dxfs>` can overwrite a cell format
Number formats are collected from anywhere in `styles.xml`. Differential formats — used by
conditional formatting — live in `<dxfs>` and carry their own ids. One colliding with a custom id
(164 and up) flips a column between numbers and dates.

**Matters when** a file uses conditional formatting *and* custom number formats, and the ids collide.
Fix by tracking whether the reader is inside `<numFmts>`, as it already does for `<cellXfs>`.

### Number formats the reader does not know are dates
`IsBuiltInDateFormat` accepts 14–22 and 45–47. The specification also reserves 27–36 and 50–58 for
dates in East Asian locales. A cell using one reads as a number.
Expand All @@ -40,11 +32,6 @@ dates in East Asian locales. A cell using one reads as a number.
The attribute says the format is not applied. Honouring it would change whether a styled cell is read
as a date.

### `t="b"` accepts only `"1"`, and `date1904` only `"1"` and `"true"`
The schema type is `xsd:boolean`, which also permits `"true"`/`"false"` and `"0"`. A writer using the
long spelling produces a boolean read as false, or a 1904 workbook read as 1900 — the latter is a
four-year error.

### Relationship targets are not percent-decoded
Parts are found through the package relationships, and targets are resolved against their folder,
`../` included. A target that percent-encodes its name (`sheet%201.xml`) is not decoded, so it is
Expand Down
65 changes: 48 additions & 17 deletions src/TriasDev.Tabular/Xlsx/XlsxCursor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -627,8 +627,7 @@ private RawCell ReadValue(SheetScanner scanner, CellValueType type, bool dateSty
: RawCell.Empty;

case CellValueType.Boolean:
// "1" as the format says, or "true" as the Open XML SDK writes it.
return RawCell.FromBoolean(text.SequenceEqual("1") || text.Equals("true", StringComparison.OrdinalIgnoreCase));
return BooleanValue(text);

case CellValueType.Error:
return RawCell.FromError(new string(text));
Expand Down Expand Up @@ -656,6 +655,22 @@ private RawCell ReadValue(SheetScanner scanner, CellValueType type, bool dateSty
: RawCell.FromNumber(value);
}

/// <summary>
/// xsd:boolean's spellings — "1" as the format writes it, "true" as the Open XML SDK does — and
/// anything else as its text: silently false is the worst reading of a value that is no boolean.
/// </summary>
private static RawCell BooleanValue(ReadOnlySpan<char> text)
{
if (text.SequenceEqual("1") || text.Equals("true", StringComparison.OrdinalIgnoreCase))
{
return RawCell.FromBoolean(true);
}

return text.SequenceEqual("0") || text.Equals("false", StringComparison.OrdinalIgnoreCase)
? RawCell.FromBoolean(false)
: RawCell.FromText(new string(text));
}

/// <summary>
/// Joins a value's text nodes up to the end of its element, which it consumes.
/// </summary>
Expand Down Expand Up @@ -1264,7 +1279,7 @@ private bool[] ReadDateStyles(CancellationToken cancellationToken)

Dictionary<int, string> customFormats = [];
List<int> cellFormats = [];
bool inCellXfs = false;
StyleSection section = StyleSection.Other;

using Stream stream = part.Open();
using XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings { IgnoreWhitespace = true });
Expand All @@ -1290,52 +1305,68 @@ private bool[] ReadDateStyles(CancellationToken cancellationToken)
$"The style table holds more than the {_options.MaxCellFormats} cell formats allowed.");
}

if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "cellXfs")
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName is "cellXfs" or "numFmts")
{
inCellXfs = false;
section = StyleSection.Other;
continue;
}

if (reader.NodeType == XmlNodeType.Element)
{
inCellXfs = ReadStyleElement(reader, inCellXfs, customFormats, cellFormats);
section = ReadStyleElement(reader, section, customFormats, cellFormats);
}
}

return FlattenDateStyles(cellFormats, customFormats);
}

/// <summary>Where in the style table the reader is: only two of its lists describe cell formats.</summary>
private enum StyleSection
{
Other,
NumberFormats,
CellFormats,
}

/// <summary>
/// Takes what one element of the style table contributes, and says whether the reader is now
/// inside <c>&lt;cellXfs&gt;</c>.
/// Takes what one element of the style table contributes, and says which section the reader is
/// now in.
/// </summary>
private bool ReadStyleElement(
/// <remarks>
/// A <c>&lt;numFmt&gt;</c> counts only inside <c>&lt;numFmts&gt;</c>. A differential format under
/// <c>&lt;dxfs&gt;</c> — conditional formatting — carries one too, with an id the cell formats may
/// already use, and taken as a cell format it turned an amount column into dates (#48).
/// </remarks>
private StyleSection ReadStyleElement(
XmlReader reader,
bool inCellXfs,
StyleSection section,
Dictionary<int, string> customFormats,
List<int> cellFormats)
{
switch (reader.LocalName)
{
case "numFmt":
case "numFmts" when !reader.IsEmptyElement:
return StyleSection.NumberFormats;

case "numFmt" when section == StyleSection.NumberFormats:
string? code = reader.GetAttribute("formatCode");

if (code is not null && TryParseFormatId(reader, out int numFmtId))
{
customFormats[numFmtId] = Bounded(code, "number format code");
}

return inCellXfs;
return section;

case "cellXfs":
return true;
case "cellXfs" when !reader.IsEmptyElement:
return StyleSection.CellFormats;

case "xf" when inCellXfs:
case "xf" when section == StyleSection.CellFormats:
cellFormats.Add(TryParseFormatId(reader, out int formatId) ? formatId : 0);
return true;
return section;

default:
return inCellXfs;
return section;
}
}

Expand Down
12 changes: 12 additions & 0 deletions tests/TriasDev.Tabular.Tests/Xlsx/ProducerSpellingsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,18 @@ public void ReadsABooleanInTheSpellingsXmlSchemaAllows(string written, bool mean
Assert.Equal(RawCell.FromBoolean(meant), row[0]);
}

[Theory]
[InlineData("yes")]
[InlineData("2")]
[InlineData("")]
public void ReadsABooleanCellHoldingSomethingElseAsItsText(string written)
{
// Silently false is the worst reading of a value that is no boolean at all (#49).
RawCell[] row = FirstRow(new XlsxPackage().WithSheet("S", $"""<row r="1"><c r="A1" t="b"><v>{written}</v></c></row>"""));

Assert.Equal(RawCell.FromText(written), row[0]);
}

[Fact]
public void ReadsLineEndsWrittenAsTheyAreAsXmlDoes()
{
Expand Down
17 changes: 17 additions & 0 deletions tests/TriasDev.Tabular.Tests/Xlsx/XlsxCursorEdgeCaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,23 @@ public void TakesTheLastDefinitionWhenANumberFormatIsDeclaredTwice()
Assert.Equal(RawCellKind.Date, cursor.CurrentRow[0].Kind);
}

[Fact]
public void KeepsACellFormatWhenAConditionalFormatReusesItsId()
{
// A differential format for conditional formatting carries its own numFmt, and its id may be
// one the cell formats already use. Taken as a cell format, "yyyy-mm-dd" overwrote "0.00" and
// an amount of 45000.25 read as 15 March 2023 (#48).
byte[] content = new XlsxPackage()
.WithStyles("""<?xml version="1.0"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="1"><numFmt numFmtId="164" formatCode="0.00"/></numFmts><cellXfs count="2"><xf numFmtId="0"/><xf numFmtId="164" applyNumberFormat="1"/></cellXfs><dxfs count="1"><dxf><numFmt numFmtId="164" formatCode="yyyy-mm-dd"/></dxf></dxfs></styleSheet>""")
.WithSheet("Sheet1", """<row r="1"><c r="A1" s="1"><v>45000.25</v></c></row>""")
.Build();

using XlsxCursor cursor = new(new MemoryStream(content, writable: false));

Assert.True(cursor.ReadRow(TestContext.Current.CancellationToken));
Assert.Equal(RawCell.FromNumber(45000.25), cursor.CurrentRow[0]);
}

[Fact]
public void ReadsAPackageWhosePartsAreNamedInAnotherCase()
{
Expand Down
Loading