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
4 changes: 4 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@
* text=auto eol=lf
*.{cmd,[cC][mM][dD]} text eol=crlf
*.{bat,[bB][aA][tT]} text eol=crlf

# Producer fixtures are read byte for byte: no line-ending conversion.
tests/TriasDev.Tabular.Tests/Fixtures/Producers/* -text
tests/TriasDev.Tabular.Tests/Fixtures/Producers/*.md text
4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,10 @@ emit. Tests go through the public API; `InternalsVisibleTo` exists for the few u
by design (`ColumnProfiler`, `HypothesisBuilder`, `Windows1252Encoding`, a diagnostics counter) —
not a licence to test implementation details elsewhere.

`Fixtures/Producers` is the exception: one small table as ClosedXML, the Open XML SDK, EPPlus, NPOI,
MiniExcel, Sylvan and LibreOffice write it, committed as they wrote it and embedded in the test
assembly, so the readers answer to real producers too. Its README says how to regenerate them.

`GoldenFixtureTests` holds both cursors to the golden fixtures. The parser candidates from the
ADR-0001 spike were removed once the decision was recorded; they remain in git history.

Expand Down
83 changes: 83 additions & 0 deletions benchmarks/TriasDev.Tabular.Comparison/OpenXmlProducer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using System.Globalization;

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace TriasDev.Tabular.Comparison;

// The SDK builds its trees through params constructors that also take an IEnumerable; every call
// here is the params form on purpose.
#pragma warning disable S3220

/// <summary>The producer table written through the Open XML SDK, the way code that uses it directly would.</summary>
internal static class OpenXmlProducer
{
public static void Write(string path)
{
using SpreadsheetDocument document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook);
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();

WorkbookStylesPart styles = workbookPart.AddNewPart<WorkbookStylesPart>();
styles.Stylesheet = new Stylesheet(
new NumberingFormats(new NumberingFormat { NumberFormatId = 164, FormatCode = "yyyy-mm-dd hh:mm:ss" }) { Count = 1 },
new Fonts(new Font()) { Count = 1 },
new Fills(new Fill()) { Count = 1 },
new Borders(new Border()) { Count = 1 },
new CellFormats(
new CellFormat(),
new CellFormat { NumberFormatId = 14, ApplyNumberFormat = true },
new CellFormat { NumberFormatId = 164, ApplyNumberFormat = true })
{ Count = 3 });

Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
SheetData data = AddSheet(workbookPart, sheets, ProducerFixtures.SheetName, 1);

data.Append(OpenXmlRow(1, [.. ProducerFixtures.Header]));

for (int r = 0; r < ProducerFixtures.Rows.Length; r++)
{
data.Append(OpenXmlRow((uint)(r + 2), ProducerFixtures.Rows[r]));
}

data.Append(OpenXmlRow(7, [ProducerFixtures.Merged]));
data.Parent!.InsertAfter(new MergeCells(new MergeCell { Reference = "A7:B7" }) { Count = 1 }, data);
AddSheet(workbookPart, sheets, ProducerFixtures.SecondSheetName, 2).Append(OpenXmlRow(1, [ProducerFixtures.Second]));
}

private static SheetData AddSheet(WorkbookPart workbookPart, Sheets sheets, string name, uint id)
{
WorksheetPart part = workbookPart.AddNewPart<WorksheetPart>();
SheetData data = new();
part.Worksheet = new Worksheet(data);
sheets.Append(new Sheet { Id = workbookPart.GetIdOfPart(part), SheetId = id, Name = name });
return data;
}

private static Row OpenXmlRow(uint number, object?[] values)
{
Row row = new() { RowIndex = number };

for (int c = 0; c < values.Length; c++)
{
string reference = $"{(char)('A' + c)}{number}";

Cell? cell = values[c] switch
{
string text => new Cell { CellReference = reference, DataType = CellValues.InlineString, InlineString = new InlineString(new Text(text) { Space = SpaceProcessingModeValues.Preserve }) },
double amount => new Cell { CellReference = reference, CellValue = new CellValue(amount) },
bool flag => new Cell { CellReference = reference, DataType = CellValues.Boolean, CellValue = new CellValue(flag) },
DateTime date => new Cell { CellReference = reference, StyleIndex = c == 3 ? 1U : 2U, CellValue = new CellValue(date.ToOADate().ToString("R", CultureInfo.InvariantCulture)) },
_ => null,
};

if (cell is not null)
{
row.Append(cell);
}
}

return row;
}
}
229 changes: 229 additions & 0 deletions benchmarks/TriasDev.Tabular.Comparison/ProducerFixtures.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
using System.Data;

using ClosedXML.Excel;

using MiniExcelLibs;

using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;

using OfficeOpenXml;

using Sylvan.Data.Excel;

namespace TriasDev.Tabular.Comparison;

/// <summary>
/// Writes one small table with each xlsx writer this project references, so the tests can hold the
/// reader to what real producers emit rather than to what our own fixture builder does.
/// </summary>
/// <remarks>
/// The files are committed under <c>tests/TriasDev.Tabular.Tests/Fixtures/Producers</c>; rerun this
/// only to add a producer or change the table, and the test beside them says what each must read as.
/// </remarks>
internal static class ProducerFixtures
{
public const string SheetName = "Data";

public const string SecondSheetName = "Zweite & <Seite>";

public const string Merged = "merged";

public const string Second = "second";

public static readonly string[] Header = ["text", "integer", "decimal", "date", "datetime", "boolean", "gap", "note"];

/// <summary>The table's rows, header excluded: text, integer, decimal, date, date and time, boolean, nothing, note.</summary>
public static readonly object?[][] Rows =
[
["plain", 42d, 1.5d, At(2024, 1, 15), At(2024, 1, 15, 10, 30, 0), true, null, "line one\nline two"],
[" padded ", -7d, 0.1d, At(1900, 3, 1), At(1999, 12, 31, 23, 59, 59), false, null, "tab\there"],
["<&>\"'", 1e15, 123456.789d, At(2000, 2, 29), At(2038, 1, 19, 3, 14, 7), true, null, "😀 ä ß €"],
["_x000D_ as typed", 0d, -0.5d, At(9999, 12, 31), At(1970, 1, 1, 0, 0, 1), false, null, "carriage\r\nreturn"],
];

private static DateTime At(int year, int month, int day, int hour = 0, int minute = 0, int second = 0) =>
new(year, month, day, hour, minute, second, DateTimeKind.Unspecified);

public static int Write(string folder)
{
Directory.CreateDirectory(folder);

Run(folder, "closedxml.xlsx", WriteClosedXml);
Run(folder, "openxml-sdk.xlsx", OpenXmlProducer.Write);
Run(folder, "epplus4.xlsx", WriteEpplus);
Run(folder, "npoi.xlsx", WriteNpoi);
Run(folder, "miniexcel.xlsx", WriteMiniExcel);
Run(folder, "sylvan.xlsx", WriteSylvan);
return 0;
}

private static void Run(string folder, string name, Action<string> write)
{
string path = Path.Combine(folder, name);
File.Delete(path);
write(path);
Console.WriteLine($"{name}\t{new FileInfo(path).Length} bytes");
}

private static void WriteClosedXml(string path)
{
using XLWorkbook workbook = new();
IXLWorksheet sheet = workbook.Worksheets.Add(SheetName);

for (int c = 0; c < Header.Length; c++)
{
sheet.Cell(1, c + 1).Value = Header[c];
}

for (int r = 0; r < Rows.Length; r++)
{
for (int c = 0; c < Rows[r].Length; c++)
{
IXLCell cell = sheet.Cell(r + 2, c + 1);

switch (Rows[r][c])
{
case string text:
cell.Value = text;
break;
case double number:
cell.Value = number;
break;
case bool flag:
cell.Value = flag;
break;
case DateTime date:
cell.Value = date;
cell.Style.NumberFormat.Format = c == 3 ? "yyyy-mm-dd" : "yyyy-mm-dd hh:mm:ss";
break;
}
}
}

sheet.Range("A7:B7").Merge();
sheet.Cell(7, 1).Value = Merged;
workbook.Worksheets.Add(SecondSheetName).Cell(1, 1).Value = Second;
workbook.SaveAs(path);
}

private static void WriteEpplus(string path)
{
using ExcelPackage package = new();
ExcelWorksheet sheet = package.Workbook.Worksheets.Add(SheetName);

for (int c = 0; c < Header.Length; c++)
{
sheet.Cells[1, c + 1].Value = Header[c];
}

for (int r = 0; r < Rows.Length; r++)
{
for (int c = 0; c < Rows[r].Length; c++)
{
if (Rows[r][c] is not { } value)
{
continue;
}

sheet.Cells[r + 2, c + 1].Value = value;

if (value is DateTime)
{
sheet.Cells[r + 2, c + 1].Style.Numberformat.Format = c == 3 ? "yyyy-mm-dd" : "yyyy-mm-dd hh:mm:ss";
}
}
}

sheet.Cells["A7:B7"].Merge = true;
sheet.Cells[7, 1].Value = Merged;
package.Workbook.Worksheets.Add(SecondSheetName).Cells[1, 1].Value = Second;
package.SaveAs(new FileInfo(path));
}

private static void WriteNpoi(string path)
{
XSSFWorkbook workbook = new();
ISheet sheet = workbook.CreateSheet(SheetName);
IDataFormat formats = workbook.CreateDataFormat();
ICellStyle dateStyle = workbook.CreateCellStyle();
dateStyle.DataFormat = formats.GetFormat("yyyy-mm-dd");
ICellStyle dateTimeStyle = workbook.CreateCellStyle();
dateTimeStyle.DataFormat = formats.GetFormat("yyyy-mm-dd hh:mm:ss");

IRow header = sheet.CreateRow(0);

for (int c = 0; c < Header.Length; c++)
{
header.CreateCell(c).SetCellValue(Header[c]);
}

for (int r = 0; r < Rows.Length; r++)
{
IRow row = sheet.CreateRow(r + 1);

for (int c = 0; c < Rows[r].Length; c++)
{
switch (Rows[r][c])
{
case string text:
row.CreateCell(c).SetCellValue(text);
break;
case double number:
row.CreateCell(c).SetCellValue(number);
break;
case bool flag:
row.CreateCell(c).SetCellValue(flag);
break;
case DateTime date:
ICell cell = row.CreateCell(c);
cell.SetCellValue(date);
cell.CellStyle = c == 3 ? dateStyle : dateTimeStyle;
break;
}
}
}

sheet.CreateRow(6).CreateCell(0).SetCellValue(Merged);
sheet.AddMergedRegion(new CellRangeAddress(6, 6, 0, 1));
workbook.CreateSheet(SecondSheetName).CreateRow(0).CreateCell(0).SetCellValue(Second);

using FileStream file = File.Create(path);
workbook.Write(file);
}

private static void WriteMiniExcel(string path)
{
// MiniExcel writes a header from the keys of the first row, and no merged cells.
List<Dictionary<string, object?>> rows = [.. Rows.Select(row => Header.Zip(row).ToDictionary(p => p.First, p => p.Second))];
Dictionary<string, object> sheets = new()
{
[SheetName] = rows,
[SecondSheetName] = new[] { new Dictionary<string, object?> { [Second] = null } },
};

MiniExcel.SaveAs(path, sheets);
}

private static void WriteSylvan(string path)
{
// Sylvan writes a header from the reader's column names, one sheet per reader, and no merged cells.
using DataTable table = new();

foreach ((string name, object? sample) in Header.Zip(Rows[0]))
{
table.Columns.Add(name, sample?.GetType() ?? typeof(string));
}

foreach (object?[] row in Rows)
{
object[] values = [.. row.Select(v => v ?? DBNull.Value)];
table.Rows.Add(values);
}

using ExcelDataWriter writer = ExcelDataWriter.Create(path);
using DataTableReader reader = table.CreateDataReader();
writer.Write(reader, SheetName);
}
}
5 changes: 5 additions & 0 deletions benchmarks/TriasDev.Tabular.Comparison/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public static int Main(string[] args)
return Measure(args[1], args[2], args[3][0]);
}

if (args.Length == 2 && args[0] == "write-producers")
{
return ProducerFixtures.Write(args[1]);
}

return Drive();
}

Expand Down
49 changes: 49 additions & 0 deletions src/TriasDev.Tabular/Xlsx/OoxmlEscapes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Globalization;
using System.Text;

namespace TriasDev.Tabular.Xlsx;

/// <summary>
/// ECMA-376's escape for a character in a string: <c>_xHHHH_</c>, the character's UTF-16 code in hex,
/// with <c>_x005F_</c> for an underscore that would otherwise start one.
/// </summary>
/// <remarks>
/// Writers use it for what XML cannot hold — a carriage return, a control character — and some for
/// much more: MiniExcel spells an emoji as its two surrogates. Read raw, a typed <c>_x000D_</c>, which
/// most writers escape as <c>_x005F_x000D_</c>, comes back as text nobody wrote.
/// </remarks>
internal static class OoxmlEscapes
{
/// <summary>The value with its escapes resolved; the same instance when it holds none.</summary>
public static string Decode(string value)
{
int at = value.IndexOf("_x", StringComparison.Ordinal);

if (at < 0)
{
return value;
}

StringBuilder? decoded = null;
int copied = 0;

while (at >= 0)
{
if (at + 7 <= value.Length
&& value[at + 6] == '_'
&& int.TryParse(value.AsSpan(at + 2, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out int code))
{
decoded ??= new StringBuilder(value.Length);
decoded.Append(value, copied, at - copied).Append((char)code);
copied = at + 7;
at = value.IndexOf("_x", copied, StringComparison.Ordinal);
}
else
{
at = value.IndexOf("_x", at + 1, StringComparison.Ordinal);
}
}

return decoded is null ? value : decoded.Append(value, copied, value.Length - copied).ToString();
}
}
Loading
Loading