Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Convert XLS, ODS and TSV spreadsheets without LibreOffice

KnifeLemon616fbbcc6d17
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 7fbcbe54..01236c82 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -34,6 +34,7 @@
<PackageVersion Include="Unhwp" Version="0.13.0" />
<PackageVersion Include="Markdig" Version="1.4.0" />
<PackageVersion Include="ExcelNumberFormat" Version="1.1.0" />
+ <PackageVersion Include="ExcelDataReader" Version="3.9.0" />
</ItemGroup>
<ItemGroup Label="Tests">
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 05fb3bc0..4a171cc9 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -20,6 +20,7 @@ Each component remains under its own license.
| Unhwp | MIT | https://github.com/iyulab/unhwp |
| Markdig | BSD-2-Clause | https://github.com/xoofx/markdig |
| ExcelNumberFormat | MIT | https://github.com/andersnm/ExcelNumberFormat |
+| ExcelDataReader | MIT | https://github.com/ExcelDataReader/ExcelDataReader |
| pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx |
| Microsoft.Extensions.* | MIT | https://github.com/dotnet/runtime |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 15adb4d1..91d077b7 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -10,13 +10,13 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
-| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet) |
-| **HWPX writer** | built in | **DOCX, XLSX, CSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc |
+| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) |
+| **HWPX writer** | built in | **DOCX, XLSX, XLS, ODS, CSV, TSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
-| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT |
+| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, PPT, RTF, ODT and ODP → PDF and to each other, output as DOCX/ODT/XLS; HWP/HWPX → DOCX/ODT |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT |
-DOCX, XLSX and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX
+DOCX, XLSX, XLS, ODS and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX
and rendered by rhwp. LibreOffice's cost is set so the built-in route always wins where one exists.
Filee never uses software installed on the system (Microsoft Office, an installed LibreOffice, programs on `PATH`):
@@ -58,7 +58,7 @@ Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) an
- pictures inline and floating, text boxes, rectangles/ellipses/lines with solid or gradient fills, groups;
- footnotes, endnotes, bookmarks, hyperlinks (web and within the document, e.g. a table of contents);
- Word's document grid ("lines"), which 한글 does not have, as an "at least" line spacing.
-- **XLSX and CSV** (`Office/Sheets`): every visible sheet becomes a section with one table. Cells show what Excel
+- **XLSX, XLS, ODS, CSV and TSV** (`Office/Sheets`, see [Spreadsheets](#spreadsheets)): every visible sheet becomes a section with one table. Cells show what Excel
shows (number formats via ExcelNumberFormat, dates, percentages, cached formula results), with fonts, fills,
borders, alignment and merged cells; frozen top rows repeat on every page. The page is A4 with narrow margins,
landscape when the columns are much wider than portrait, and the table is scaled to the page width like
@@ -92,6 +92,30 @@ text) and LibreOffice + H2Orestart (opens it), see `tests/Filee.Engines.Tests/Do
Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
+## Spreadsheets
+
+`SpreadsheetConverter` (engine id `spreadsheet`) converts between XLSX, XLS (also `.xlt`), ODS, CSV and TSV (also
+`.tab`) in-process; every format goes through one in-memory workbook (`Office/Sheets/Workbook.cs`) whose cells keep
+the text the spreadsheet shows, the value behind it and its Excel number format.
+
+| Format | Read | Written |
+|---|---|---|
+| XLSX | own reader: values, number formats, fonts, fills, borders, alignment, merges, widths, heights, hidden rows / columns / sheets, frozen rows | every sheet, numbers and dates as numbers with their formats, booleans, styles, merges, widths, heights, hidden rows / columns, frozen rows |
+| XLS (Excel 97–2003, also Excel 5/95) | ExcelDataReader (MIT): values, number formats, merges, horizontal / vertical alignment; widths, heights and hidden rows / columns from the BIFF records (`XlsLayout.cs`) | no (LibreOffice) |
+| ODS | own reader (`content.xml`, `styles.xml`, `settings.xml`): repeated rows / columns (the empty repeats up to the end of the sheet are skipped), spans, every value type, the text Calc shows (`text:p`), data styles as Excel codes, cell styles, widths, heights, hidden rows / columns / sheets, frozen and header rows | every sheet, typed cells (float, percentage, currency, date, time, boolean) with data styles and the shown text, styles, merges, widths, heights, hidden rows / columns, frozen rows |
+| CSV / TSV | delimiter (CSV: comma, semicolon or tab; TSV: tab) and encoding (UTF-8 / UTF-16 with BOM, else CP949) | UTF-8 with BOM, CRLF, one file per sheet |
+
+- Number formats: Excel codes and OpenDocument data styles are converted both ways (`OdsNumberStyles.cs`) for
+ digits, decimals, grouping, thousands scaling, percent, scientific, currency symbols, literal text, colours,
+ positive / negative / zero sections, dates, times and durations. Codes with conditions (`[>100]`), fractions or
+ text between digits are written as plain numbers (General).
+- Column widths use Excel's unit (a digit of Calibri 11 = 7 px); in ODS a character is 5.25 pt. LibreOffice
+ measures with its own fonts, so a width can differ by up to a fifth after LibreOffice opens the file.
+- XLS cells keep the default font, fill and borders (ExcelDataReader does not expose them); XLS output still
+ needs LibreOffice. Password-protected XLS and ODS files stop with a clear message.
+- Not converted: formulas (their cached results are kept), charts, pictures, comments, conditional formatting,
+ data validation, print areas and page breaks.
+
## HWP ↔ HWPX
rhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goes
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index af7d20a6..8d2cc57b 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -18,6 +18,7 @@
<PackageReference Include="Unhwp" />
<PackageReference Include="Markdig" />
<PackageReference Include="ExcelNumberFormat" />
+ <PackageReference Include="ExcelDataReader" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
index 4c0b2c3a..c4b8a88b 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
@@ -59,6 +59,7 @@ public sealed class HwpxConverter : IConverter
Path.GetDirectoryName(Path.GetFullPath(step.InputPath))!),
"xlsx" => SheetDocument.Build(XlsxReader.Read(step.InputPath)),
"csv" => SheetDocument.Build(CsvFormat.Read(step.InputPath)),
+ "xls" or "ods" or "tsv" => SheetDocument.Build(SpreadsheetConverter.Read(step.InputPath, step.From)),
"pptx" => PptxReader.Read(step.InputPath, media),
_ => await ReadWithPandocAsync(step, media, cancellationToken),
};
@@ -142,7 +143,8 @@ public sealed class HwpxConverter : IConverter
private static List<ConversionEdge> BuildEdges(bool pandoc)
{
- List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "hwpx"), new("md", "hwpx"), new("xlsx", "hwpx"), new("csv", "hwpx"), new("pptx", "hwpx")];
+ List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "hwpx"), new("md", "hwpx"), new("xlsx", "hwpx"), new("csv", "hwpx"), new("pptx", "hwpx"),
+ new("xls", "hwpx"), new("ods", "hwpx"), new("tsv", "hwpx")];
if (pandoc)
edges.AddRange(PandocReaders.Keys.Select(from => new ConversionEdge(from, "hwpx")));
return edges;
diff --git a/src/Filee.Engines/Office/Sheets/CsvFormat.cs b/src/Filee.Engines/Office/Sheets/CsvFormat.cs
index e9b98347..7d873a40 100644
--- a/src/Filee.Engines/Office/Sheets/CsvFormat.cs
+++ b/src/Filee.Engines/Office/Sheets/CsvFormat.cs
@@ -1,6 +1,7 @@
-// CSV ↔ Worksheet. Reading follows RFC 4180 (quotes, doubled quotes, line breaks inside quotes), detects the
-// delimiter (comma, semicolon or tab) and the encoding (UTF-8 / UTF-16 with BOM, else CP949 like Korean Excel).
-// Writing produces what Excel opens correctly everywhere: UTF-8 with BOM, CRLF line ends, quotes only when needed.
+// CSV / TSV ↔ Worksheet. Reading follows RFC 4180 (quotes, doubled quotes, line breaks inside quotes), detects the
+// CSV delimiter (comma, semicolon or tab; TSV is always tab) and the encoding (UTF-8 / UTF-16 with BOM, else CP949
+// like Korean Excel). Writing produces what Excel opens correctly everywhere: UTF-8 with BOM, CRLF line ends,
+// quotes only when needed.
using System.Globalization;
using System.Text;
@@ -10,12 +11,20 @@ namespace Filee.Engines.Office.Sheets;
internal static class CsvFormat
{
+ /// <summary>The TSV delimiter.</summary>
+ public const char Tab = '\t';
+
/// <summary>Reads a CSV file into one sheet named after the file.</summary>
- public static Workbook Read(string path)
+ public static Workbook Read(string path) => Read(path, delimiter: null);
+
+ /// <summary>Reads a TSV file (tab-separated, whatever other characters it holds).</summary>
+ public static Workbook ReadTsv(string path) => Read(path, Tab);
+
+ private static Workbook Read(string path, char? delimiter)
{
var text = HwpxConverter.DecodeText(File.ReadAllBytes(path));
var sheet = new Worksheet(Path.GetFileNameWithoutExtension(path));
- var rows = Parse(text, DetectDelimiter(text));
+ var rows = Parse(text, delimiter ?? DetectDelimiter(text));
var widths = new Dictionary<int, double>();
for (var r = 0; r < rows.Count; r++)
{
@@ -24,7 +33,9 @@ internal static class CsvFormat
var value = rows[r][c];
if (value.Length == 0)
continue;
- sheet.Set(r, c, new SheetCell(value, CellStyle.Default, IsNumber(value)));
+ sheet.Set(r, c, IsNumber(value)
+ ? new SheetCell(value, CellStyle.Default, IsNumber: true) { Value = double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture) }
+ : new SheetCell(value, CellStyle.Default));
widths[c] = Math.Max(widths.GetValueOrDefault(c), DisplayWidth(value));
}
}
@@ -36,8 +47,8 @@ internal static class CsvFormat
return book;
}
- /// <summary>Writes the used range of a sheet as CSV (UTF-8 with BOM, CRLF).</summary>
- public static void Write(Worksheet sheet, string path)
+ /// <summary>Writes the used range of a sheet as CSV, or as TSV with <see cref="Tab"/> (UTF-8 with BOM, CRLF).</summary>
+ public static void Write(Worksheet sheet, string path, char delimiter = ',')
{
var sb = new StringBuilder();
if (sheet.UsedRange() is { } range)
@@ -50,10 +61,10 @@ internal static class CsvFormat
for (var c = 0; c <= range.Right; c++)
{
if (!sheet.HiddenColumns.Contains(c))
- fields.Add(Quote(sheet.Get(r, c)?.Text ?? ""));
+ fields.Add(Quote(sheet.Get(r, c)?.Text ?? "", delimiter));
}
// Excel omits trailing empty fields only for fully empty rows; keep the column count stable.
- sb.Append(string.Join(',', fields)).Append("\r\n");
+ sb.Append(string.Join(delimiter, fields)).Append("\r\n");
}
}
File.WriteAllText(path, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
@@ -131,8 +142,8 @@ internal static class CsvFormat
return counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key == ',' ? 0 : 1).First().Key;
}
- private static string Quote(string value) =>
- value.IndexOfAny([',', '"', '\r', '\n']) >= 0 || value.StartsWith(' ') || value.EndsWith(' ')
+ private static string Quote(string value, char delimiter) =>
+ value.IndexOfAny([delimiter, '"', '\r', '\n']) >= 0 || value.StartsWith(' ') || value.EndsWith(' ')
? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\""
: value;
diff --git a/src/Filee.Engines/Office/Sheets/NumberFormatter.cs b/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
new file mode 100644
index 00000000..f96b733e
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
@@ -0,0 +1,99 @@
+// Excel number formats → the text a cell shows, shared by the XLSX, XLS and ODS readers so a value looks the same
+// whichever file it came from. Formatting is done by ExcelNumberFormat (MIT); dates are Excel serial days.
+
+using System.Globalization;
+using ExcelNumberFormat;
+
+namespace Filee.Engines.Office.Sheets;
+
+/// <summary>Formats cell values with Excel number format codes; parsed formats are cached per instance.</summary>
+internal sealed class NumberFormatter(bool date1904 = false)
+{
+ /// <summary>Built-in number formats (ECMA-376 18.8.30); 14 uses the ISO date order most locales read.</summary>
+ public static readonly IReadOnlyDictionary<int, string> BuiltInFormats = new Dictionary<int, string>
+ {
+ [0] = "General",
+ [1] = "0",
+ [2] = "0.00",
+ [3] = "#,##0",
+ [4] = "#,##0.00",
+ [9] = "0%",
+ [10] = "0.00%",
+ [11] = "0.00E+00",
+ [12] = "# ?/?",
+ [13] = "# ??/??",
+ [14] = "yyyy-mm-dd",
+ [15] = "d-mmm-yy",
+ [16] = "d-mmm",
+ [17] = "mmm-yy",
+ [18] = "h:mm AM/PM",
+ [19] = "h:mm:ss AM/PM",
+ [20] = "h:mm",
+ [21] = "h:mm:ss",
+ [22] = "yyyy-mm-dd h:mm",
+ [37] = "#,##0 ;(#,##0)",
+ [38] = "#,##0 ;[Red](#,##0)",
+ [39] = "#,##0.00;(#,##0.00)",
+ [40] = "#,##0.00;[Red](#,##0.00)",
+ [45] = "mm:ss",
+ [46] = "[h]:mm:ss",
+ [47] = "mmss.0",
+ [48] = "##0.0E+0",
+ [49] = "@",
+ };
+
+ private readonly Dictionary<string, NumberFormat> _formats = [];
+
+ /// <summary>True for a missing format or "General" (any case).</summary>
+ public static bool IsGeneral(string? format) =>
+ string.IsNullOrEmpty(format) || format.Equals("General", StringComparison.OrdinalIgnoreCase);
+
+ /// <summary>The text Excel shows for <paramref name="value"/> under <paramref name="format"/>.</summary>
+ public string Format(double value, string? format)
+ {
+ if (IsGeneral(format) || Parse(format!) is not { } parsed)
+ return General(value);
+ try
+ {
+ return parsed.Format(value, CultureInfo.InvariantCulture, date1904);
+ }
+ catch (Exception ex) when (ex is ArgumentException or FormatException or OverflowException)
+ {
+ return General(value);
+ }
+ }
+
+ /// <summary>True when <paramref name="format"/> shows a date or time of day (not a duration like [h]:mm).</summary>
+ public bool IsDate(string? format) =>
+ !IsGeneral(format) && Parse(format!) is { IsDateTimeFormat: true, IsTimeSpanFormat: false };
+
+ private NumberFormat? Parse(string format)
+ {
+ if (!_formats.TryGetValue(format, out var parsed))
+ _formats[format] = parsed = new NumberFormat(format);
+ return parsed.IsValid ? parsed : null;
+ }
+
+ /// <summary>Excel's General format: up to 11 significant characters, no trailing zeros.</summary>
+ public static string General(double value)
+ {
+ if (value == Math.Floor(value) && Math.Abs(value) < 1e11)
+ return value.ToString("0", CultureInfo.InvariantCulture);
+ var text = value.ToString("G10", CultureInfo.InvariantCulture);
+ return text.Contains('E') ? value.ToString("0.#####E+00", CultureInfo.InvariantCulture) : text;
+ }
+
+ /// <summary>
+ /// A date as Excel serial days. Excel counts the non-existent 29 February 1900, so its serials before
+ /// 1 March 1900 are one lower than OLE Automation dates.
+ /// </summary>
+ public static double ToSerial(DateTime date)
+ {
+ var oa = date.ToOADate();
+ return oa is >= 1 and < 61 ? oa - 1 : oa;
+ }
+
+ /// <summary>The date of an Excel serial (the inverse of <see cref="ToSerial"/>).</summary>
+ public static DateTime FromSerial(double serial) =>
+ DateTime.FromOADate(serial is >= 0 and < 60 ? serial + 1 : serial);
+}
diff --git a/src/Filee.Engines/Office/Sheets/OdsNumberStyles.cs b/src/Filee.Engines/Office/Sheets/OdsNumberStyles.cs
new file mode 100644
index 00000000..c526dbe3
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/OdsNumberStyles.cs
@@ -0,0 +1,607 @@
+// Excel number format codes ↔ OpenDocument data styles (number:number-style, number:date-style, ...), so an ODS
+// written from XLSX / XLS keeps what the cells show and an XLSX written from ODS keeps real number formats.
+// Covered: digits with decimals, grouping and thousands scaling, percent, scientific, currency symbols, literal
+// text, colours, positive / negative (/ zero) sections, dates, times and durations. Anything else (conditions,
+// fractions written as Excel codes, text between digits, eras) falls back to General.
+
+using System.Globalization;
+using System.Security;
+using System.Text;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal static class OdsNumberStyles
+{
+ public static readonly XNamespace Number = "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0";
+ public static readonly XNamespace Style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0";
+ public static readonly XNamespace Fo = "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0";
+
+ /// <summary>LibreOffice's name for number:min-decimal-places in ODF 1.2 files.</summary>
+ private static readonly XNamespace Loext = "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0";
+
+ /// <summary>Excel's named colours ([Red]) and their RGB values.</summary>
+ private static readonly Dictionary<string, string> Colors = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["Black"] = "#000000",
+ ["Blue"] = "#0000FF",
+ ["Cyan"] = "#00FFFF",
+ ["Green"] = "#00FF00",
+ ["Magenta"] = "#FF00FF",
+ ["Red"] = "#FF0000",
+ ["White"] = "#FFFFFF",
+ ["Yellow"] = "#FFFF00",
+ };
+
+ // ───────────────────────── OpenDocument → Excel ─────────────────────────
+
+ /// <summary>
+ /// The Excel format code of a data style, or null when it has none Excel could use (boolean styles,
+ /// unsupported parts). <paramref name="find"/> looks up the styles that style:map applies.
+ /// </summary>
+ public static string? ToExcel(XElement style, Func<string, XElement?> find)
+ {
+ var main = SectionCode(style);
+ if (main is null)
+ return null;
+ var maps = style.Elements(Style + "map")
+ .Select(m => (Condition: ((string?)m.Attribute(Style + "condition") ?? "").Replace(" ", "", StringComparison.Ordinal),
+ Target: find((string?)m.Attribute(Style + "apply-style-name") ?? "")))
+ .ToList();
+ string? Mapped(string condition) =>
+ maps.FirstOrDefault(m => m.Condition == condition).Target is { } target ? SectionCode(target) : null;
+
+ // LibreOffice keeps the last section in the style itself and maps the others by condition.
+ if (Mapped("value()>=0") is { } positive)
+ return positive + ";" + main;
+ if (Mapped("value()>0") is { } plus && Mapped("value()<0") is { } minus)
+ return plus + ";" + minus + ";" + main;
+ return main;
+ }
+
+ private static string? SectionCode(XElement style)
+ {
+ var kind = style.Name.LocalName;
+ var isDate = kind is "date-style" or "time-style";
+ var elapsed = (string?)style.Attribute(Number + "truncate-on-overflow") == "false";
+ var sb = new StringBuilder();
+ if ((string?)style.Element(Style + "text-properties")?.Attribute(Fo + "color") is { } color &&
+ Colors.FirstOrDefault(c => c.Value.Equals(color, StringComparison.OrdinalIgnoreCase)).Key is { } colorName)
+ sb.Append('[').Append(colorName).Append(']');
+
+ foreach (var part in style.Elements().Where(e => e.Name.Namespace == Number))
+ {
+ var isLong = (string?)part.Attribute(Number + "style") == "long";
+ switch (part.Name.LocalName)
+ {
+ case "text" when kind == "percentage-style":
+ // The percent sign is part of the text; everything around it is literal.
+ var pieces = part.Value.Split('%');
+ sb.Append(string.Join("%", pieces.Select(p => Literal(p, isDate: false))));
+ break;
+ case "text":
+ sb.Append(Literal(part.Value, isDate));
+ break;
+ case "number":
+ sb.Append(Digits(part));
+ break;
+ case "scientific-number":
+ var mantissa = Math.Max(1, Int(part, "min-integer-digits") ?? 1);
+ var places = Int(part, "decimal-places") ?? 0;
+ sb.Append('0', mantissa);
+ if (places > 0)
+ sb.Append('.').Append('0', places);
+ sb.Append("E+").Append('0', Math.Max(1, Int(part, "min-exponent-digits") ?? 2));
+ break;
+ case "fraction":
+ if (Int(part, "min-integer-digits") is > 0)
+ sb.Append("# ");
+ sb.Append('?', Math.Max(1, Int(part, "min-numerator-digits") ?? 1)).Append('/');
+ if (Int(part, "denominator-value") is { } denominator)
+ sb.Append(denominator.ToString(CultureInfo.InvariantCulture));
+ else
+ sb.Append('?', Math.Max(1, Int(part, "min-denominator-digits") ?? 1));
+ break;
+ case "currency-symbol":
+ sb.Append(Literal(part.Value, isDate: false));
+ break;
+ case "year":
+ sb.Append(isLong ? "yyyy" : "yy");
+ break;
+ case "month":
+ sb.Append(((string?)part.Attribute(Number + "textual") == "true", isLong) switch
+ {
+ (true, true) => "mmmm",
+ (true, false) => "mmm",
+ (false, true) => "mm",
+ _ => "m",
+ });
+ break;
+ case "day":
+ sb.Append(isLong ? "dd" : "d");
+ break;
+ case "day-of-week":
+ sb.Append(isLong ? "dddd" : "ddd");
+ break;
+ case "hours":
+ var hours = isLong ? "hh" : "h";
+ sb.Append(elapsed ? "[" + hours + "]" : hours);
+ break;
+ case "minutes":
+ sb.Append(isLong ? "mm" : "m");
+ break;
+ case "seconds":
+ sb.Append(isLong ? "ss" : "s");
+ if (Int(part, "decimal-places") is > 0 and var decimals)
+ sb.Append('.').Append('0', decimals);
+ break;
+ case "am-pm":
+ sb.Append("AM/PM");
+ break;
+ case "text-content":
+ sb.Append('@');
+ break;
+ case "fill-character":
+ break;
+ default:
+ return null; // boolean, era, quarter, week of year: nothing Excel shows the same way
+ }
+ }
+ return sb.ToString();
+ }
+
+ /// <summary>number:number → "#,##0.00" and the like; "General" when it gives no decimal places.</summary>
+ private static string Digits(XElement number)
+ {
+ if (Int(number, "decimal-places") is not { } places)
+ return "General";
+ var minPlaces = Math.Min(places, Int(number, "min-decimal-places") ?? (int?)number.Attribute(Loext + "min-decimal-places") ?? places);
+ var minInteger = Int(number, "min-integer-digits") ?? 1;
+ var sb = new StringBuilder();
+ if ((string?)number.Attribute(Number + "grouping") == "true")
+ {
+ var integer = new string('0', minInteger).PadLeft(4, '#');
+ sb.Append(integer.AsSpan(0, integer.Length - 3)).Append(',').Append(integer.AsSpan(integer.Length - 3));
+ }
+ else
+ {
+ sb.Append(minInteger > 0 ? new string('0', minInteger) : "#");
+ }
+ if (places > 0)
+ sb.Append('.').Append('0', minPlaces).Append('#', places - minPlaces);
+ if (double.TryParse((string?)number.Attribute(Number + "display-factor"), NumberStyles.Float, CultureInfo.InvariantCulture, out var factor))
+ {
+ for (; factor >= 1000; factor /= 1000)
+ sb.Append(',');
+ }
+ return sb.ToString();
+ }
+
+ private static int? Int(XElement element, string attribute) =>
+ int.TryParse((string?)element.Attribute(Number + attribute), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null;
+
+ /// <summary>
+ /// Literal text in an Excel code: unquoted when Excel shows those characters as they are, otherwise in quotes
+ /// (a quote itself is escaped with a backslash).
+ /// </summary>
+ private static string Literal(string text, bool isDate)
+ {
+ var plain = isDate ? " -/:.,()$+" : " -:()$+";
+ if (text.All(ch => plain.Contains(ch)))
+ return text;
+ return string.Join("\\\"", text.Split('"').Select(p => p.Length == 0 ? "" : "\"" + p + "\""));
+ }
+
+ // ───────────────────────── Excel → OpenDocument ─────────────────────────
+
+ private enum Kind
+ {
+ Literal,
+ Digit,
+ Point,
+ Comma,
+ Percent,
+ Exponent,
+ Slash,
+ Year,
+ Month,
+ Minute,
+ Day,
+ Hour,
+ Second,
+ AmPm,
+ Text,
+ Color,
+ Currency,
+ General,
+ Unsupported,
+ }
+
+ private readonly record struct Token(Kind Kind, string Text, bool Elapsed = false);
+
+ /// <summary>One section of a format code as a data style body.</summary>
+ private sealed record Section(string Element, string Body, string? Color, bool Elapsed);
+
+ /// <summary>
+ /// The data style for an Excel format code: XML of the style named <paramref name="name"/> (plus the styles its
+ /// sections map to) and the office:value-type its cells use. Null for General, text formats and codes that have
+ /// no data style equivalent; such cells are written as plain numbers.
+ /// </summary>
+ public static (string Xml, string ValueType)? ToOdf(string? code, string name)
+ {
+ if (NumberFormatter.IsGeneral(code))
+ return null;
+ var sections = SplitSections(code!);
+ if (sections.Count > 4)
+ return null;
+ // The fourth section formats text cells: nothing to do for numbers.
+ var parsed = sections.Take(3).Select(s => BuildSection(Tokenize(s))).ToList();
+ if (parsed.Any(p => p is null) || parsed[0]!.Element == "text-style")
+ return null;
+ var first = parsed[0]!;
+ var element = first.Element;
+ if (parsed.Count > 1 && element is "date-style" or "time-style")
+ parsed = [first]; // dates with several sections are rare; the first one shows positive dates
+
+ var sb = new StringBuilder();
+ string StyleXml(string styleName, Section section, string maps) =>
+ $"<number:{element} style:name=\"{styleName}\"{(styleName == name ? "" : " style:volatile=\"true\"")}" +
+ (section.Elapsed ? " number:truncate-on-overflow=\"false\"" : "") + ">" +
+ (section.Color is { } color ? $"<style:text-properties fo:color=\"{color}\"/>" : "") +
+ section.Body + maps + $"</number:{element}>";
+
+ switch (parsed.Count)
+ {
+ case 1:
+ sb.Append(StyleXml(name, first, ""));
+ break;
+ case 2:
+ sb.Append(StyleXml(name + "P0", first, ""));
+ sb.Append(StyleXml(name, parsed[1]!, $"<style:map style:condition=\"value()&gt;=0\" style:apply-style-name=\"{name}P0\"/>"));
+ break;
+ default:
+ sb.Append(StyleXml(name + "P0", first, ""));
+ sb.Append(StyleXml(name + "P1", parsed[1]!, ""));
+ sb.Append(StyleXml(name, parsed[2]!,
+ $"<style:map style:condition=\"value()&gt;0\" style:apply-style-name=\"{name}P0\"/><style:map style:condition=\"value()&lt;0\" style:apply-style-name=\"{name}P1\"/>"));
+ break;
+ }
+ var valueType = element switch
+ {
+ "percentage-style" => "percentage",
+ "currency-style" => "currency",
+ "date-style" => "date",
+ "time-style" => "time",
+ _ => "float",
+ };
+ return (sb.ToString(), valueType);
+ }
+
+ /// <summary>Splits at ";" outside quotes, brackets and escapes.</summary>
+ private static List<string> SplitSections(string code)
+ {
+ var sections = new List<string>();
+ var start = 0;
+ var quoted = false;
+ var bracket = false;
+ for (var i = 0; i < code.Length; i++)
+ {
+ var ch = code[i];
+ if (ch == '\\' && !quoted)
+ i++;
+ else if (ch == '"')
+ quoted = !quoted;
+ else if (!quoted && ch == '[')
+ bracket = true;
+ else if (!quoted && ch == ']')
+ bracket = false;
+ else if (!quoted && !bracket && ch == ';')
+ {
+ sections.Add(code[start..i]);
+ start = i + 1;
+ }
+ }
+ sections.Add(code[start..]);
+ return sections;
+ }
+
+ private static List<Token> Tokenize(string section)
+ {
+ if (section.Trim().Equals("General", StringComparison.OrdinalIgnoreCase))
+ return [new Token(Kind.General, "")];
+ var tokens = new List<Token>();
+ for (var i = 0; i < section.Length; i++)
+ {
+ var ch = section[i];
+ switch (ch)
+ {
+ case '"':
+ var end = section.IndexOf('"', i + 1);
+ end = end < 0 ? section.Length : end;
+ tokens.Add(new Token(Kind.Literal, section[(i + 1)..end]));
+ i = end;
+ break;
+ case '\\':
+ if (++i < section.Length)
+ tokens.Add(new Token(Kind.Literal, section[i].ToString()));
+ break;
+ case '_':
+ i++; // room as wide as the next character: a space is close enough
+ tokens.Add(new Token(Kind.Literal, " "));
+ break;
+ case '*':
+ i++; // repeat the next character to fill the cell: nothing in a fixed layout
+ break;
+ case '[':
+ var close = section.IndexOf(']', i + 1);
+ if (close < 0)
+ return [new Token(Kind.Unsupported, "")];
+ tokens.Add(Bracket(section[(i + 1)..close]));
+ i = close;
+ break;
+ case '0' or '#' or '?':
+ tokens.Add(new Token(Kind.Digit, ch.ToString()));
+ break;
+ case '.':
+ tokens.Add(new Token(Kind.Point, "."));
+ break;
+ case ',':
+ tokens.Add(new Token(Kind.Comma, ","));
+ break;
+ case '%':
+ tokens.Add(new Token(Kind.Percent, "%"));
+ break;
+ case '/':
+ tokens.Add(new Token(Kind.Slash, "/"));
+ break;
+ case '@':
+ tokens.Add(new Token(Kind.Text, "@"));
+ break;
+ case 'E' or 'e' when i + 1 < section.Length && section[i + 1] is '+' or '-':
+ tokens.Add(new Token(Kind.Exponent, "E" + section[++i]));
+ break;
+ default:
+ if (AmPmLength(section, i) is > 0 and var length)
+ {
+ tokens.Add(new Token(Kind.AmPm, section.Substring(i, length)));
+ i += length - 1;
+ break;
+ }
+ var kind = char.ToLowerInvariant(ch) switch
+ {
+ 'y' => Kind.Year,
+ 'm' => Kind.Month,
+ 'd' => Kind.Day,
+ 'h' => Kind.Hour,
+ 's' => Kind.Second,
+ 'e' or 'g' or 'b' => Kind.Unsupported, // era and Buddhist years
+ _ => Kind.Literal,
+ };
+ var run = 1;
+ if (kind != Kind.Literal)
+ {
+ while (i + run < section.Length && char.ToLowerInvariant(section[i + run]) == char.ToLowerInvariant(ch))
+ run++;
+ }
+ tokens.Add(new Token(kind, kind == Kind.Literal ? ch.ToString() : new string(char.ToLowerInvariant(ch), run)));
+ i += run - 1;
+ break;
+ }
+ }
+
+ // "m" means minutes right after hours or right before seconds.
+ for (var i = 0; i < tokens.Count; i++)
+ {
+ if (tokens[i].Kind != Kind.Month)
+ continue;
+ var before = tokens.Take(i).LastOrDefault(t => IsDatePart(t.Kind));
+ var after = tokens.Skip(i + 1).FirstOrDefault(t => IsDatePart(t.Kind));
+ if (before.Kind == Kind.Hour || after.Kind == Kind.Second)
+ tokens[i] = tokens[i] with { Kind = Kind.Minute };
+ }
+ return tokens;
+ }
+
+ private static bool IsDatePart(Kind kind) => kind is Kind.Year or Kind.Month or Kind.Minute or Kind.Day or Kind.Hour or Kind.Second or Kind.AmPm;
+
+ private static int AmPmLength(string text, int index)
+ {
+ foreach (var marker in new[] { "AM/PM", "A/P" })
+ {
+ if (string.Compare(text, index, marker, 0, marker.Length, StringComparison.OrdinalIgnoreCase) == 0)
+ return marker.Length;
+ }
+ return 0;
+ }
+
+ /// <summary>[Red], [$₩-412], [h], [&gt;100], ...</summary>
+ private static Token Bracket(string inner)
+ {
+ if (inner.StartsWith('$'))
+ {
+ var dash = inner.IndexOf('-', StringComparison.Ordinal);
+ var symbol = dash < 0 ? inner[1..] : inner[1..dash];
+ return symbol.Length > 0 ? new Token(Kind.Currency, symbol) : new Token(Kind.Literal, "");
+ }
+ if (inner.Length > 0 && inner.All(ch => char.ToLowerInvariant(ch) == char.ToLowerInvariant(inner[0])) && char.ToLowerInvariant(inner[0]) is 'h' or 'm' or 's')
+ {
+ var kind = char.ToLowerInvariant(inner[0]) switch { 'h' => Kind.Hour, 'm' => Kind.Minute, _ => Kind.Second };
+ return new Token(kind, inner.ToLowerInvariant(), Elapsed: true);
+ }
+ // Conditions ([>100]), numbered colours and number systems ([DBNum1]) change what is shown.
+ return Colors.TryGetValue(inner, out var color) ? new Token(Kind.Color, color) : new Token(Kind.Unsupported, inner);
+ }
+
+ private static Section? BuildSection(List<Token> tokens)
+ {
+ if (tokens.Any(t => t.Kind == Kind.Unsupported))
+ return null;
+ if (tokens.Any(t => t.Kind == Kind.Text))
+ return new Section("text-style", "", null, false);
+ var color = tokens.LastOrDefault(t => t.Kind == Kind.Color).Text;
+ return tokens.Any(t => IsDatePart(t.Kind)) ? DateSection(tokens, color) : NumberSection(tokens, color);
+ }
+
+ private static Section? DateSection(List<Token> tokens, string? color)
+ {
+ var body = new StringBuilder();
+ var literal = new StringBuilder();
+ void Flush()
+ {
+ if (literal.Length > 0)
+ body.Append("<number:text>").Append(Escape(literal.ToString())).Append("</number:text>");
+ literal.Clear();
+ }
+ var elapsed = false;
+ for (var i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var length = token.Text.Trim('[', ']').Length;
+ switch (token.Kind)
+ {
+ case Kind.Literal or Kind.Point or Kind.Comma or Kind.Slash or Kind.Percent:
+ literal.Append(token.Text);
+ continue;
+ case Kind.Color:
+ continue;
+ case Kind.Digit or Kind.Exponent or Kind.Currency or Kind.General:
+ return null;
+ }
+ Flush();
+ switch (token.Kind)
+ {
+ case Kind.Year:
+ body.Append(length > 2 ? "<number:year number:style=\"long\"/>" : "<number:year/>");
+ break;
+ case Kind.Month:
+ body.Append(length switch
+ {
+ 1 => "<number:month/>",
+ 2 => "<number:month number:style=\"long\"/>",
+ 3 or 5 => "<number:month number:textual=\"true\"/>",
+ _ => "<number:month number:style=\"long\" number:textual=\"true\"/>",
+ });
+ break;
+ case Kind.Day:
+ body.Append(length switch
+ {
+ 1 => "<number:day/>",
+ 2 => "<number:day number:style=\"long\"/>",
+ 3 => "<number:day-of-week/>",
+ _ => "<number:day-of-week number:style=\"long\"/>",
+ });
+ break;
+ case Kind.Hour:
+ elapsed |= token.Elapsed;
+ body.Append(length > 1 ? "<number:hours number:style=\"long\"/>" : "<number:hours/>");
+ break;
+ case Kind.Minute:
+ body.Append(length > 1 ? "<number:minutes number:style=\"long\"/>" : "<number:minutes/>");
+ break;
+ case Kind.Second:
+ // Fractions of a second: "ss.00".
+ var places = 0;
+ if (i + 1 < tokens.Count && tokens[i + 1].Kind == Kind.Point)
+ {
+ while (i + 2 + places < tokens.Count && tokens[i + 2 + places] is { Kind: Kind.Digit, Text: "0" })
+ places++;
+ if (places > 0)
+ i += 1 + places;
+ }
+ body.Append(CultureInfo.InvariantCulture, $"<number:seconds{(length > 1 ? " number:style=\"long\"" : "")}{(places > 0 ? $" number:decimal-places=\"{places}\"" : "")}/>");
+ break;
+ case Kind.AmPm:
+ body.Append("<number:am-pm/>");
+ break;
+ }
+ }
+ Flush();
+ var isDate = tokens.Any(t => t.Kind is Kind.Year or Kind.Month or Kind.Day);
+ return new Section(isDate ? "date-style" : "time-style", body.ToString(), color, elapsed && !isDate);
+ }
+
+ private static Section? NumberSection(List<Token> tokens, string? color)
+ {
+ if (tokens.Any(t => t.Kind == Kind.Slash))
+ return null; // fractions
+ var start = tokens.FindIndex(t => t.Kind is Kind.Digit or Kind.Point or Kind.General);
+ var end = start;
+ if (start >= 0)
+ {
+ while (end + 1 < tokens.Count && tokens[end + 1].Kind is Kind.Digit or Kind.Point or Kind.Comma or Kind.Exponent)
+ end++;
+ if (tokens.Skip(end + 1).Any(t => t.Kind is Kind.Digit or Kind.Point or Kind.General))
+ return null; // text between the digits ("000-0000")
+ }
+
+ var body = new StringBuilder();
+ var literal = new StringBuilder();
+ void Flush()
+ {
+ if (literal.Length > 0)
+ body.Append("<number:text>").Append(Escape(literal.ToString())).Append("</number:text>");
+ literal.Clear();
+ }
+ var percent = false;
+ var currency = false;
+ for (var i = 0; i < tokens.Count; i++)
+ {
+ if (i == start)
+ {
+ Flush();
+ body.Append(tokens[i].Kind == Kind.General ? "<number:number number:min-integer-digits=\"1\"/>" : Digits(tokens[start..(end + 1)]));
+ i = end;
+ continue;
+ }
+ var token = tokens[i];
+ switch (token.Kind)
+ {
+ case Kind.Percent:
+ percent = true;
+ literal.Append('%');
+ break;
+ case Kind.Currency:
+ currency = true;
+ Flush();
+ body.Append("<number:currency-symbol>").Append(Escape(token.Text)).Append("</number:currency-symbol>");
+ break;
+ case Kind.Literal or Kind.Comma or Kind.Point:
+ literal.Append(token.Text);
+ break;
+ }
+ }
+ Flush();
+ return new Section(currency ? "currency-style" : percent ? "percentage-style" : "number-style", body.ToString(), color, false);
+ }
+
+ /// <summary>The digits of a number section → number:number or number:scientific-number.</summary>
+ private static string Digits(List<Token> digits)
+ {
+ var exponent = digits.FindIndex(t => t.Kind == Kind.Exponent);
+ var mantissa = exponent < 0 ? digits : digits[..exponent];
+ var point = mantissa.FindIndex(t => t.Kind == Kind.Point);
+ var integer = point < 0 ? mantissa : mantissa[..point];
+ var fraction = point < 0 ? [] : mantissa[(point + 1)..];
+
+ var minInteger = integer.Count(t => t.Text == "0");
+ var lastIntegerDigit = integer.FindLastIndex(t => t.Kind == Kind.Digit);
+ var grouping = integer.Take(Math.Max(0, lastIntegerDigit)).Any(t => t.Kind == Kind.Comma);
+ // Commas after the last digit divide by 1000 each ("#,##0,").
+ var scaling = mantissa.Skip(mantissa.FindLastIndex(t => t.Kind == Kind.Digit) + 1).Count(t => t.Kind == Kind.Comma);
+ var places = fraction.Count(t => t.Kind == Kind.Digit);
+ var minPlaces = fraction.Count(t => t.Text == "0");
+
+ if (exponent >= 0)
+ {
+ var exponentDigits = digits[(exponent + 1)..].Count(t => t.Kind == Kind.Digit);
+ return string.Create(CultureInfo.InvariantCulture,
+ $"<number:scientific-number number:decimal-places=\"{places}\" number:min-integer-digits=\"{Math.Max(1, minInteger)}\" number:min-exponent-digits=\"{Math.Max(1, exponentDigits)}\"/>");
+ }
+ return string.Create(CultureInfo.InvariantCulture,
+ $"<number:number number:decimal-places=\"{places}\" number:min-decimal-places=\"{minPlaces}\" number:min-integer-digits=\"{minInteger}\"") +
+ (grouping ? " number:grouping=\"true\"" : "") +
+ (scaling > 0 ? string.Create(CultureInfo.InvariantCulture, $" number:display-factor=\"{Math.Pow(1000, scaling)}\"") : "") + "/>";
+ }
+
+ private static string Escape(string text) => SecurityElement.Escape(text) ?? "";
+}
diff --git a/src/Filee.Engines/Office/Sheets/OdsReader.cs b/src/Filee.Engines/Office/Sheets/OdsReader.cs
new file mode 100644
index 00000000..4563816f
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/OdsReader.cs
@@ -0,0 +1,518 @@
+// ODS (OpenDocument spreadsheet, LibreOffice Calc) → Workbook, read directly from content.xml, styles.xml and
+// settings.xml without LibreOffice: sheets, repeated rows and columns (the huge empty repeats that end every sheet
+// are skipped, not expanded), merged cells, values with the text Calc shows (the cached text:p), number formats as
+// Excel codes (OdsNumberStyles), cell styles (font, colour, fill, borders, alignment, wrapping), column widths, row
+// heights, hidden rows / columns / sheets and frozen rows. Charts, images, comments and conditional formats are
+// not read.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using System.Xml;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal sealed class OdsReader
+{
+ private static readonly XNamespace Office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0";
+ private static readonly XNamespace Table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0";
+ private static readonly XNamespace Text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0";
+ private static readonly XNamespace Config = "urn:oasis:names:tc:opendocument:xmlns:config:1.0";
+ private static readonly XNamespace Manifest = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0";
+ private static readonly XNamespace Style = OdsNumberStyles.Style;
+ private static readonly XNamespace Fo = OdsNumberStyles.Fo;
+ private static readonly XNamespace Number = OdsNumberStyles.Number;
+
+ /// <summary>Excel's sheet size; ODS sheets repeat their last empty row and column up to (at least) it.</summary>
+ private const int MaxRows = 1_048_576;
+ private const int MaxColumns = 16_384;
+
+ /// <summary>
+ /// Empty but formatted cells repeated more often than this are the formatted rest of a row or sheet (a coloured
+ /// column, a bordered page), not content worth a table cell each.
+ /// </summary>
+ private const int MaxStyledRepeat = 256;
+
+ /// <summary>Points per character of column width (7 pixels of Calibri 11 at 96 dpi), as in the XLSX writer.</summary>
+ internal const double PointsPerCharacter = 5.25;
+
+ private readonly Dictionary<(string Family, string Name), XElement> _styles = [];
+ private readonly Dictionary<string, XElement> _dataStyles = [];
+ private readonly Dictionary<string, (CellStyle Style, string? DataStyle)> _cellStyles = [];
+ private readonly Dictionary<string, string?> _formats = [];
+ private readonly Dictionary<string, int> _frozenRows = [];
+ private readonly NumberFormatter _formatter = new();
+ private XElement? _defaultCellStyle;
+
+ /// <summary>Reads every visible sheet of <paramref name="path"/>.</summary>
+ public static Workbook Read(string path)
+ {
+ using var zip = ZipFile.OpenRead(path);
+ if (IsEncrypted(zip))
+ throw new InvalidDataException("The spreadsheet is protected with a password (encrypted). Remove the password in LibreOffice and convert it again.");
+ var content = Load(zip, "content.xml") ?? throw new InvalidDataException("The file is not an OpenDocument spreadsheet (no content.xml).");
+ var spreadsheet = content.Root?.Element(Office + "body")?.Element(Office + "spreadsheet")
+ ?? throw new InvalidDataException("The file is not an OpenDocument spreadsheet (no office:spreadsheet).");
+
+ var reader = new OdsReader();
+ reader.ReadStyles(Load(zip, "styles.xml"), content);
+ reader.ReadSettings(Load(zip, "settings.xml"));
+ var book = new Workbook();
+ foreach (var table in spreadsheet.Elements(Table + "table"))
+ {
+ var tableStyle = reader.Find("table", (string?)table.Attribute(Table + "style-name"));
+ if ((string?)tableStyle?.Element(Style + "table-properties")?.Attribute(Table + "display") != "false")
+ book.Sheets.Add(reader.ReadTable(table));
+ }
+ return book;
+ }
+
+ private static XDocument? Load(ZipArchive zip, string name)
+ {
+ if (zip.GetEntry(name) is not { } entry)
+ return null;
+ using var stream = entry.Open();
+ // Whitespace is meaningful inside paragraphs (a space between two spans).
+ return XDocument.Load(stream, LoadOptions.PreserveWhitespace);
+ }
+
+ /// <summary>Encrypted packages keep a readable manifest that lists how each part is encrypted.</summary>
+ private static bool IsEncrypted(ZipArchive zip) =>
+ Load(zip, "META-INF/manifest.xml")?.Descendants(Manifest + "encryption-data").Any() == true;
+
+ // ───────────────────────── Styles ─────────────────────────
+
+ private void ReadStyles(XDocument? styles, XDocument content)
+ {
+ var containers = new[]
+ {
+ styles?.Root?.Element(Office + "styles"),
+ styles?.Root?.Element(Office + "automatic-styles"),
+ content.Root?.Element(Office + "automatic-styles"),
+ };
+ foreach (var element in containers.Where(c => c is not null).SelectMany(c => c!.Elements()))
+ {
+ var name = (string?)element.Attribute(Style + "name");
+ if (element.Name == Style + "default-style" && (string?)element.Attribute(Style + "family") == "table-cell")
+ _defaultCellStyle = element;
+ else if (element.Name == Style + "style" && name is not null)
+ _styles[((string?)element.Attribute(Style + "family") ?? "", name)] = element;
+ else if (element.Name.Namespace == Number && name is not null)
+ _dataStyles[name] = element;
+ }
+ }
+
+ private XElement? Find(string family, string? name) =>
+ name is not null && _styles.TryGetValue((family, name), out var style) ? style : null;
+
+ /// <summary>A cell style with its parents and the default style applied, and its data style name.</summary>
+ private (CellStyle Style, string? DataStyle) CellStyleOf(string? name)
+ {
+ name ??= "Default";
+ if (_cellStyles.TryGetValue(name, out var cached))
+ return cached;
+
+ var chain = new List<XElement>();
+ for (var style = Find("table-cell", name); style is not null && chain.Count < 20; style = Find("table-cell", (string?)style.Attribute(Style + "parent-style-name")))
+ chain.Insert(0, style);
+ if (_defaultCellStyle is not null)
+ chain.Insert(0, _defaultCellStyle);
+
+ var props = new StyleProperties();
+ string? dataStyle = null;
+ foreach (var style in chain)
+ {
+ props.Apply(style);
+ dataStyle = (string?)style.Attribute(Style + "data-style-name") ?? dataStyle;
+ }
+ return _cellStyles[name] = (props.ToCellStyle(), dataStyle);
+ }
+
+ /// <summary>The Excel format code of a data style (cached), null when there is none.</summary>
+ private string? FormatOf(string? dataStyle)
+ {
+ if (dataStyle is null)
+ return null;
+ if (!_formats.TryGetValue(dataStyle, out var format))
+ {
+ _formats[dataStyle] = format = _dataStyles.TryGetValue(dataStyle, out var style)
+ ? OdsNumberStyles.ToExcel(style, name => _dataStyles.GetValueOrDefault(name))
+ : null;
+ }
+ return format;
+ }
+
+ /// <summary>Formatting properties of one style; unset ones inherit from the parent style.</summary>
+ private sealed class StyleProperties
+ {
+ private bool? _bold, _italic, _underline, _strike, _wrap;
+ private double? _size;
+ private string? _color, _fill, _textAlign, _alignSource, _verticalAlign;
+ private CellBorder? _left, _right, _top, _bottom;
+
+ public void Apply(XElement style)
+ {
+ if (style.Element(Style + "text-properties") is { } text)
+ {
+ if ((Attr(text, Fo + "font-weight") ?? Attr(text, Style + "font-weight-asian")) is { } weight)
+ _bold = weight == "bold" || int.TryParse(weight, out var w) && w >= 600;
+ if ((Attr(text, Fo + "font-style") ?? Attr(text, Style + "font-style-asian")) is { } italic)
+ _italic = italic is "italic" or "oblique";
+ if (Attr(text, Style + "text-underline-style") is { } underline)
+ _underline = underline != "none";
+ if (Attr(text, Style + "text-line-through-style") is { } strike)
+ _strike = strike != "none";
+ if (Points(Attr(text, Fo + "font-size")) is { } size)
+ _size = size;
+ if (Color(Attr(text, Fo + "color")) is { } color)
+ _color = color;
+ }
+ if (style.Element(Style + "table-cell-properties") is { } cell)
+ {
+ if (Attr(cell, Fo + "background-color") is { } fill)
+ _fill = fill == "transparent" ? null : Color(fill);
+ if (Attr(cell, Fo + "border") is { } all)
+ _left = _right = _top = _bottom = Border(all);
+ _left = Border(Attr(cell, Fo + "border-left")) ?? _left;
+ _right = Border(Attr(cell, Fo + "border-right")) ?? _right;
+ _top = Border(Attr(cell, Fo + "border-top")) ?? _top;
+ _bottom = Border(Attr(cell, Fo + "border-bottom")) ?? _bottom;
+ _verticalAlign = Attr(cell, Style + "vertical-align") ?? _verticalAlign;
+ if (Attr(cell, Fo + "wrap-option") is { } wrap)
+ _wrap = wrap == "wrap";
+ _alignSource = Attr(cell, Style + "text-align-source") ?? _alignSource;
+ }
+ if (Attr(style.Element(Style + "paragraph-properties"), Fo + "text-align") is { } align)
+ _textAlign = align;
+ }
+
+ public CellStyle ToCellStyle() => new()
+ {
+ Bold = _bold ?? false,
+ Italic = _italic ?? false,
+ Underline = _underline ?? false,
+ Strike = _strike ?? false,
+ FontSize = _size,
+ Color = _color,
+ Fill = _fill,
+ // "value-type" = Calc's automatic alignment (numbers right, text left), like Excel's General.
+ Align = _alignSource == "value-type" ? CellAlign.General : _textAlign switch
+ {
+ "start" or "left" or "justify" => CellAlign.Left,
+ "center" => CellAlign.Center,
+ "end" or "right" => CellAlign.Right,
+ _ => CellAlign.General,
+ },
+ VerticalAlign = _verticalAlign switch
+ {
+ "top" => CellVerticalAlign.Top,
+ "middle" => CellVerticalAlign.Center,
+ _ => CellVerticalAlign.Bottom,
+ },
+ Wrap = _wrap ?? false,
+ Left = _left ?? CellBorder.None,
+ Right = _right ?? CellBorder.None,
+ Top = _top ?? CellBorder.None,
+ Bottom = _bottom ?? CellBorder.None,
+ };
+
+ private static string? Attr(XElement? element, XName name) => (string?)element?.Attribute(name);
+
+ /// <summary>"0.75pt solid #000000" → the Excel border style of that weight and pattern.</summary>
+ private static CellBorder? Border(string? value)
+ {
+ if (value is null)
+ return null;
+ var parts = value.Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ var pattern = parts.FirstOrDefault(p => p is "solid" or "dotted" or "dashed" or "dot-dash" or "dot-dot-dash" or "double" or "groove" or "ridge" or "inset" or "outset" or "fine-dashed" or "dash-dot" or "dash-dot-dot" or "none" or "hidden");
+ if (pattern is null or "none" or "hidden")
+ return CellBorder.None;
+ var width = parts.Select(Points).FirstOrDefault(p => p is not null) ?? 0.75;
+ var color = parts.Select(Color).FirstOrDefault(c => c is not null);
+ var style = pattern switch
+ {
+ "double" => "double",
+ "dotted" => "dotted",
+ "dashed" or "fine-dashed" => width > 1.1 ? "mediumDashed" : "dashed",
+ "dot-dash" or "dash-dot" => width > 1.1 ? "mediumDashDot" : "dashDot",
+ "dot-dot-dash" or "dash-dot-dot" => width > 1.1 ? "mediumDashDotDot" : "dashDotDot",
+ _ => width < 0.3 ? "hair" : width <= 1.1 ? "thin" : width <= 2.1 ? "medium" : "thick",
+ };
+ return new CellBorder(style, color);
+ }
+ }
+
+ /// <summary>"#1f4e79" → "#1F4E79"; null for anything else.</summary>
+ private static string? Color(string? value) =>
+ value is { Length: 7 } && value[0] == '#' && value.Skip(1).All(char.IsAsciiHexDigit) ? value.ToUpperInvariant() : null;
+
+ /// <summary>An ODF length ("2.258cm", "0.889in", "15pt") in points; null for percentages and garbage.</summary>
+ internal static double? Points(string? length)
+ {
+ if (string.IsNullOrEmpty(length))
+ return null;
+ var unit = length.TrimStart('-', '+', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
+ if (!double.TryParse(length.AsSpan(0, length.Length - unit.Length), NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
+ return null;
+ return unit switch
+ {
+ "pt" => value,
+ "in" => value * 72,
+ "cm" => value * 72 / 2.54,
+ "mm" => value * 72 / 25.4,
+ "pc" => value * 12,
+ "px" => value * 0.75,
+ _ => null,
+ };
+ }
+
+ // ───────────────────────── Settings ─────────────────────────
+
+ /// <summary>Frozen rows per sheet (the view settings Calc saves in settings.xml).</summary>
+ private void ReadSettings(XDocument? settings)
+ {
+ var tables = settings?.Descendants(Config + "config-item-map-named").FirstOrDefault(m => (string?)m.Attribute(Config + "name") == "Tables");
+ foreach (var entry in tables?.Elements(Config + "config-item-map-entry") ?? [])
+ {
+ string? Item(string name) => (string?)entry.Elements(Config + "config-item").FirstOrDefault(i => (string?)i.Attribute(Config + "name") == name);
+ if (Item("VerticalSplitMode") == "2" && int.TryParse(Item("VerticalSplitPosition"), out var rows) && rows > 0 && (string?)entry.Attribute(Config + "name") is { } sheet)
+ _frozenRows[sheet] = rows;
+ }
+ }
+
+ // ───────────────────────── Sheets ─────────────────────────
+
+ private sealed record Span(int Start, int Count, double? Size, bool Hidden, string? DefaultStyle);
+
+ private sealed record CellRun(int Column, int Count, SheetCell? Cell, int ColumnSpan, int RowSpan);
+
+ private Worksheet ReadTable(XElement table)
+ {
+ var name = (string?)table.Attribute(Table + "name") ?? "Sheet";
+ var sheet = new Worksheet(name);
+
+ var columns = new List<Span>();
+ var c = 0;
+ foreach (var (column, _) in Children(table, "table-column", "table-header-columns", "table-column-group", "table-columns"))
+ {
+ if (c >= MaxColumns)
+ break;
+ var count = Math.Min(Repeat(column, "number-columns-repeated"), MaxColumns - c);
+ var width = Points((string?)Find("table-column", (string?)column.Attribute(Table + "style-name"))?.Element(Style + "table-column-properties")?.Attribute(Style + "column-width"));
+ columns.Add(new Span(c, count, width / PointsPerCharacter, IsCollapsed(column), (string?)column.Attribute(Table + "default-cell-style-name")));
+ c += count;
+ }
+
+ var rows = new List<Span>();
+ var r = 0;
+ var headerRows = 0;
+ foreach (var (row, header) in Children(table, "table-row", "table-header-rows", "table-row-group", "table-rows"))
+ {
+ if (r >= MaxRows)
+ break;
+ var count = Math.Min(Repeat(row, "number-rows-repeated"), MaxRows - r);
+ var properties = Find("table-row", (string?)row.Attribute(Table + "style-name"))?.Element(Style + "table-row-properties");
+ // Calc saves every row's height; only rows not sized to their content have a custom one.
+ var height = (string?)properties?.Attribute(Style + "use-optimal-row-height") == "true" ? null : Points((string?)properties?.Attribute(Style + "row-height"));
+ rows.Add(new Span(r, count, height, IsCollapsed(row), null));
+ if (header && headerRows == r)
+ headerRows += count;
+
+ var cells = Cells(row, columns);
+ var hasText = cells.Any(run => run.Cell is { Text.Length: > 0 } || run.ColumnSpan > 1 || run.RowSpan > 1);
+ var copies = hasText ? count : cells.Any(run => run.Cell is not null) && count <= MaxStyledRepeat ? count : 0;
+ for (var copy = 0; copy < copies; copy++)
+ {
+ foreach (var run in cells)
+ {
+ for (var i = 0; i < run.Count; i++)
+ {
+ if (run.Cell is not null)
+ sheet.Set(r + copy, run.Column + i, run.Cell);
+ if (run.ColumnSpan > 1 || run.RowSpan > 1)
+ sheet.Merges.Add(new CellRange(r + copy, run.Column + i, r + copy + run.RowSpan - 1, run.Column + i + run.ColumnSpan - 1));
+ }
+ }
+ }
+ r += count;
+ }
+
+ // Widths, heights and hidden flags only matter where the sheet has something; the repeats reach the
+ // last row and column of the sheet.
+ var used = sheet.UsedRange();
+ var right = Math.Max(used?.Right ?? -1, sheet.Merges.Count > 0 ? sheet.Merges.Max(m => m.Right) : -1);
+ var bottom = Math.Max(used?.Bottom ?? -1, sheet.Merges.Count > 0 ? sheet.Merges.Max(m => m.Bottom) : -1);
+ foreach (var span in columns)
+ {
+ for (var i = span.Start; i < span.Start + span.Count && i <= right; i++)
+ {
+ if (span.Size is { } width)
+ sheet.ColumnWidths[i] = Math.Round(width, 4);
+ if (span.Hidden)
+ sheet.HiddenColumns.Add(i);
+ }
+ if (span.Size is { } rest && span.Start <= right + 1 && right + 1 < span.Start + span.Count)
+ sheet.DefaultColumnWidth = Math.Round(rest, 4);
+ }
+ foreach (var span in rows)
+ {
+ for (var i = span.Start; i < span.Start + span.Count && i <= bottom; i++)
+ {
+ if (span.Size is { } height)
+ sheet.RowHeights[i] = Math.Round(height, 2);
+ if (span.Hidden)
+ sheet.HiddenRows.Add(i);
+ }
+ }
+ sheet.FrozenRows = _frozenRows.TryGetValue(name, out var frozen) ? frozen : headerRows;
+ return sheet;
+ }
+
+ /// <summary>Rows (or columns) of a table in order, also inside groups; the flag marks header rows.</summary>
+ private static IEnumerable<(XElement Element, bool Header)> Children(XElement parent, string item, string header, params string[] groups)
+ {
+ foreach (var element in parent.Elements())
+ {
+ if (element.Name == Table + item)
+ yield return (element, false);
+ else if (element.Name == Table + header)
+ {
+ foreach (var (child, _) in Children(element, item, header, groups))
+ yield return (child, true);
+ }
+ else if (groups.Any(g => element.Name == Table + g))
+ {
+ foreach (var child in Children(element, item, header, groups))
+ yield return child;
+ }
+ }
+ }
+
+ private static int Repeat(XElement element, string attribute) =>
+ int.TryParse((string?)element.Attribute(Table + attribute), out var count) && count > 0 ? count : 1;
+
+ private static bool IsCollapsed(XElement element) => (string?)element.Attribute(Table + "visibility") is "collapse" or "filter";
+
+ /// <summary>The cells of one row element as runs of repeated cells; covered cells (inside a merge) stay empty.</summary>
+ private List<CellRun> Cells(XElement row, List<Span> columns)
+ {
+ var runs = new List<CellRun>();
+ var rowDefault = (string?)row.Attribute(Table + "default-cell-style-name");
+ var c = 0;
+ foreach (var element in row.Elements())
+ {
+ var covered = element.Name == Table + "covered-table-cell";
+ if (!covered && element.Name != Table + "table-cell")
+ continue;
+ if (c >= MaxColumns)
+ break;
+ var count = Math.Min(Repeat(element, "number-columns-repeated"), MaxColumns - c);
+ if (!covered)
+ {
+ var styleName = (string?)element.Attribute(Table + "style-name") ?? rowDefault ?? columns.FirstOrDefault(s => s.Start <= c && c < s.Start + s.Count)?.DefaultStyle;
+ var cell = Cell(element, styleName);
+ if (cell is { HasContent: false } || cell is { Text.Length: 0 } && count > MaxStyledRepeat)
+ cell = null;
+ var columnSpan = Repeat(element, "number-columns-spanned");
+ var rowSpan = Repeat(element, "number-rows-spanned");
+ if (cell is not null || columnSpan > 1 || rowSpan > 1)
+ runs.Add(new CellRun(c, count, cell, columnSpan, rowSpan));
+ }
+ c += count;
+ }
+ return runs;
+ }
+
+ private SheetCell Cell(XElement element, string? styleName)
+ {
+ var (style, dataStyle) = CellStyleOf(styleName);
+ var type = (string?)element.Attribute(Office + "value-type");
+ double? value = null;
+ switch (type)
+ {
+ case "float" or "percentage" or "currency":
+ if (double.TryParse((string?)element.Attribute(Office + "value"), NumberStyles.Float, CultureInfo.InvariantCulture, out var number))
+ value = number;
+ break;
+ case "date":
+ if (DateTimeOffset.TryParse((string?)element.Attribute(Office + "date-value"), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date))
+ value = NumberFormatter.ToSerial(date.DateTime);
+ break;
+ case "time":
+ try
+ {
+ value = XmlConvert.ToTimeSpan((string?)element.Attribute(Office + "time-value") ?? "").TotalDays;
+ }
+ catch (FormatException) { }
+ break;
+ case "boolean":
+ value = (string?)element.Attribute(Office + "boolean-value") is "true" or "1" ? 1 : 0;
+ break;
+ }
+
+ var text = Paragraphs(element);
+ if (type == "boolean")
+ return new SheetCell(text ?? (value == 1 ? "TRUE" : "FALSE"), style) { Value = value, IsBoolean = true };
+ if (value is not { } v)
+ return new SheetCell(text ?? (string?)element.Attribute(Office + "string-value") ?? "", style);
+
+ var format = FormatOf(dataStyle) ?? type switch
+ {
+ "date" => v == Math.Floor(v) ? "yyyy-mm-dd" : "yyyy-mm-dd hh:mm:ss",
+ "time" => "hh:mm:ss",
+ "percentage" => "0%",
+ _ => null,
+ };
+ format = NumberFormatter.IsGeneral(format) ? null : format;
+ // text:p is what Calc showed when it saved; files written by other programs may leave it out.
+ return new SheetCell(text ?? _formatter.Format(v, format), style, IsNumber: true) { Value = v, NumberFormat = format };
+ }
+
+ /// <summary>The text of a cell: its paragraphs joined by line breaks; null when it has none.</summary>
+ private static string? Paragraphs(XElement cell)
+ {
+ var paragraphs = cell.Elements().Where(e => e.Name == Text + "p" || e.Name == Text + "h").ToList();
+ if (paragraphs.Count == 0)
+ return null;
+ var sb = new StringBuilder();
+ for (var i = 0; i < paragraphs.Count; i++)
+ {
+ if (i > 0)
+ sb.Append('\n');
+ Inline(paragraphs[i], sb);
+ }
+ return sb.ToString();
+ }
+
+ private static void Inline(XElement element, StringBuilder sb)
+ {
+ foreach (var node in element.Nodes())
+ {
+ if (node is XText text)
+ {
+ // ODF collapses white space in text; extra spaces are text:s elements.
+ foreach (var ch in text.Value)
+ {
+ var c = ch is '\t' or '\r' or '\n' ? ' ' : ch;
+ if (c != ' ' || sb.Length == 0 || sb[^1] != ' ')
+ sb.Append(c);
+ }
+ }
+ else if (node is XElement child)
+ {
+ if (child.Name == Text + "s")
+ sb.Append(' ', Repeat(child, Text + "c"));
+ else if (child.Name == Text + "tab")
+ sb.Append('\t');
+ else if (child.Name == Text + "line-break")
+ sb.Append('\n');
+ else if (child.Name != Office + "annotation" && child.Name != Text + "note")
+ Inline(child, sb);
+ }
+ }
+ }
+
+ private static int Repeat(XElement element, XName attribute) =>
+ int.TryParse((string?)element.Attribute(attribute), out var count) && count > 0 ? count : 1;
+}
diff --git a/src/Filee.Engines/Office/Sheets/OdsWriter.cs b/src/Filee.Engines/Office/Sheets/OdsWriter.cs
new file mode 100644
index 00000000..83041ec8
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/OdsWriter.cs
@@ -0,0 +1,429 @@
+// Workbook → ODS (OpenDocument spreadsheet) without LibreOffice: one table per sheet with typed cells (numbers,
+// percentages, currencies, dates and times keep their value and number format as a data style, the shown text is
+// the cached text:p), booleans, text with line breaks and repeated spaces, cell styles (font, colour, fill,
+// borders, alignment), merged cells, column widths, row heights, hidden rows and columns, and frozen rows. Opens in
+// LibreOffice, Excel and Google Sheets.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Security;
+using System.Text;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal static class OdsWriter
+{
+ private const string MimeType = "application/vnd.oasis.opendocument.spreadsheet";
+ private const string Version = "1.3";
+ private const string Declaration = """<?xml version="1.0" encoding="UTF-8"?>""";
+
+ private const string Namespaces =
+ "xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" " +
+ "xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\" " +
+ "xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" " +
+ "xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" " +
+ "xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\" " +
+ "xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"";
+
+ /// <summary>Columns written per sheet: LibreOffice before 7.4 stops at 1024 and warns about anything beyond.</summary>
+ private const int SheetColumns = 1024;
+
+ /// <summary>
+ /// Excel's default font size, so a workbook from Excel keeps its proportions (LibreOffice's own default is 10 pt).
+ /// </summary>
+ private const string StylesXml = Declaration +
+ $"<office:document-styles {Namespaces} office:version=\"{Version}\"><office:styles>" +
+ "<style:default-style style:family=\"table-cell\"><style:text-properties fo:font-size=\"11pt\" style:font-size-asian=\"11pt\" style:font-size-complex=\"11pt\"/></style:default-style>" +
+ "<style:style style:name=\"Default\" style:family=\"table-cell\"/>" +
+ "</office:styles></office:document-styles>";
+
+ public static void Write(Workbook book, string path)
+ {
+ var sheets = book.Sheets.Count > 0 ? book.Sheets : [new Worksheet("Sheet1")];
+ var names = XlsxWriter.UniqueNames(sheets.Select(s => s.Name));
+ var styles = new AutomaticStyles();
+ var body = new StringBuilder();
+ for (var i = 0; i < sheets.Count; i++)
+ Table(body, sheets[i], names[i], styles);
+
+ var content = Declaration +
+ $"<office:document-content {Namespaces} office:version=\"{Version}\"><office:automatic-styles>{styles.Xml()}</office:automatic-styles>" +
+ $"<office:body><office:spreadsheet>{body}</office:spreadsheet></office:body></office:document-content>";
+ var frozen = sheets.Select((s, i) => (Name: names[i], s.FrozenRows)).Where(f => f.FrozenRows > 0).ToList();
+
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ // OpenDocument rule: "mimetype" first and stored uncompressed, so the type can be read at a fixed offset.
+ Add(zip, "mimetype", MimeType, CompressionLevel.NoCompression);
+ Add(zip, "content.xml", content);
+ Add(zip, "styles.xml", StylesXml);
+ if (frozen.Count > 0)
+ Add(zip, "settings.xml", Settings(frozen));
+ Add(zip, "META-INF/manifest.xml", Declaration +
+ $"<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"{Version}\">" +
+ $"<manifest:file-entry manifest:full-path=\"/\" manifest:version=\"{Version}\" manifest:media-type=\"{MimeType}\"/>" +
+ "<manifest:file-entry manifest:full-path=\"content.xml\" manifest:media-type=\"text/xml\"/>" +
+ "<manifest:file-entry manifest:full-path=\"styles.xml\" manifest:media-type=\"text/xml\"/>" +
+ (frozen.Count > 0 ? "<manifest:file-entry manifest:full-path=\"settings.xml\" manifest:media-type=\"text/xml\"/>" : "") +
+ "</manifest:manifest>");
+ }
+
+ private static void Table(StringBuilder sb, Worksheet sheet, string name, AutomaticStyles styles)
+ {
+ var range = sheet.UsedRange();
+ var right = range?.Right ?? 0;
+ var bottom = range?.Bottom ?? 0;
+ sb.Append(CultureInfo.InvariantCulture, $"<table:table table:name=\"{Escape(name)}\" table:style-name=\"{styles.Table()}\">");
+
+ for (var c = 0; c <= right;)
+ {
+ var width = sheet.ColumnWidth(c);
+ var hidden = sheet.HiddenColumns.Contains(c);
+ var count = 1;
+ while (c + count <= right && sheet.ColumnWidth(c + count) == width && sheet.HiddenColumns.Contains(c + count) == hidden)
+ count++;
+ sb.Append(CultureInfo.InvariantCulture, $"<table:table-column table:style-name=\"{styles.Column(width)}\"{Repeated("columns", count)}{(hidden ? " table:visibility=\"collapse\"" : "")}/>");
+ c += count;
+ }
+ // The rest of the sheet gets the workbook's default width (LibreOffice's own default is wider than Excel's).
+ if (right + 1 < SheetColumns)
+ sb.Append(CultureInfo.InvariantCulture, $"<table:table-column table:style-name=\"{styles.Column(sheet.DefaultColumnWidth)}\"{Repeated("columns", SheetColumns - right - 1)}/>");
+
+ // Merged areas: the top-left cell spans, the others are covered cells.
+ var anchors = new Dictionary<(int, int), CellRange>();
+ var covered = new HashSet<(int, int)>();
+ foreach (var merge in sheet.Merges)
+ {
+ if (anchors.ContainsKey((merge.Top, merge.Left)) || covered.Contains((merge.Top, merge.Left)))
+ continue; // overlapping merges are invalid; keep the first
+ anchors[(merge.Top, merge.Left)] = merge;
+ for (var r = merge.Top; r <= merge.Bottom; r++)
+ for (var c = merge.Left; c <= merge.Right; c++)
+ if (r != merge.Top || c != merge.Left)
+ covered.Add((r, c));
+ }
+
+ for (var r = 0; r <= bottom;)
+ {
+ var height = sheet.RowHeights.TryGetValue(r, out var points) ? points : (double?)null;
+ var hidden = sheet.HiddenRows.Contains(r);
+ var visibility = hidden ? " table:visibility=\"collapse\"" : "";
+ if (IsEmptyRow(sheet, r, right, covered))
+ {
+ // Runs of empty rows alike become one repeated row.
+ var count = 1;
+ while (r + count <= bottom && IsEmptyRow(sheet, r + count, right, covered) && sheet.HiddenRows.Contains(r + count) == hidden &&
+ (sheet.RowHeights.TryGetValue(r + count, out var next) ? next : (double?)null) == height)
+ count++;
+ sb.Append(CultureInfo.InvariantCulture, $"<table:table-row table:style-name=\"{styles.Row(height)}\"{Repeated("rows", count)}{visibility}><table:table-cell{Repeated("columns", right + 1)}/></table:table-row>");
+ r += count;
+ continue;
+ }
+
+ sb.Append(CultureInfo.InvariantCulture, $"<table:table-row table:style-name=\"{styles.Row(height)}\"{visibility}>");
+ for (var c = 0; c <= right;)
+ {
+ var cell = sheet.Get(r, c);
+ var isCovered = covered.Contains((r, c));
+ if (isCovered || cell is null && !anchors.ContainsKey((r, c)))
+ {
+ var count = 1;
+ while (c + count <= right && covered.Contains((r, c + count)) == isCovered && (isCovered || sheet.Get(r, c + count) is null && !anchors.ContainsKey((r, c + count))))
+ count++;
+ sb.Append(isCovered ? "<table:covered-table-cell" : "<table:table-cell").Append(Repeated("columns", count)).Append("/>");
+ c += count;
+ continue;
+ }
+ Cell(sb, cell, anchors.TryGetValue((r, c), out var merge) ? merge : null, styles);
+ c++;
+ }
+ sb.Append("</table:table-row>");
+ r++;
+ }
+ sb.Append("</table:table>");
+ }
+
+ private static bool IsEmptyRow(Worksheet sheet, int row, int right, HashSet<(int, int)> covered) =>
+ !sheet.Rows.ContainsKey(row) && !Enumerable.Range(0, right + 1).Any(c => covered.Contains((row, c)));
+
+ private static void Cell(StringBuilder sb, SheetCell? cell, CellRange? merge, AutomaticStyles styles)
+ {
+ sb.Append("<table:table-cell");
+ if (merge is { } m)
+ {
+ if (m.Right > m.Left)
+ sb.Append(CultureInfo.InvariantCulture, $" table:number-columns-spanned=\"{m.Right - m.Left + 1}\"");
+ if (m.Bottom > m.Top)
+ sb.Append(CultureInfo.InvariantCulture, $" table:number-rows-spanned=\"{m.Bottom - m.Top + 1}\"");
+ }
+ if (cell is null)
+ {
+ sb.Append("/>");
+ return;
+ }
+
+ var number = cell.Value ?? (cell.IsNumber && double.TryParse(cell.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed) ? parsed : null);
+ string? dataStyle = null;
+ if (cell.IsBoolean && number is { } flag)
+ {
+ sb.Append(CultureInfo.InvariantCulture, $" office:value-type=\"boolean\" office:boolean-value=\"{(flag != 0 ? "true" : "false")}\"");
+ }
+ else if (number is { } value && double.IsFinite(value))
+ {
+ var (name, valueType) = styles.DataStyle(cell.NumberFormat);
+ dataStyle = name;
+ sb.Append(Value(value, valueType));
+ }
+ else if (cell.Text.Length > 0)
+ {
+ sb.Append(" office:value-type=\"string\"");
+ }
+ if (styles.Cell(cell.Style, dataStyle) is { } styleName)
+ sb.Append(CultureInfo.InvariantCulture, $" table:style-name=\"{styleName}\"");
+
+ if (cell.Text.Length == 0)
+ {
+ sb.Append("/>");
+ return;
+ }
+ sb.Append('>');
+ Paragraphs(sb, cell.Text);
+ sb.Append("</table:table-cell>");
+ }
+
+ /// <summary>The value attributes of a number cell: dates as ISO dates, times as durations, the rest as numbers.</summary>
+ private static string Value(double value, string valueType)
+ {
+ var number = value.ToString("R", CultureInfo.InvariantCulture);
+ switch (valueType)
+ {
+ case "date" when value is > -657_000 and < 2_958_000:
+ var date = NumberFormatter.FromSerial(value);
+ var iso = date.TimeOfDay == TimeSpan.Zero
+ ? date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
+ : date.ToString(date.Millisecond == 0 ? "yyyy-MM-dd'T'HH:mm:ss" : "yyyy-MM-dd'T'HH:mm:ss.fff", CultureInfo.InvariantCulture);
+ return $" office:value-type=\"date\" office:date-value=\"{iso}\"";
+ case "time" when Math.Abs(value) < 1e7:
+ var duration = TimeSpan.FromDays(Math.Abs(value));
+ return string.Create(CultureInfo.InvariantCulture,
+ $" office:value-type=\"time\" office:time-value=\"{(value < 0 ? "-" : "")}PT{(long)duration.TotalHours}H{duration.Minutes:00}M{duration.Seconds + duration.Milliseconds / 1000.0:00.###}S\"");
+ case "percentage" or "currency":
+ return $" office:value-type=\"{valueType}\" office:value=\"{number}\"";
+ default:
+ return $" office:value-type=\"float\" office:value=\"{number}\"";
+ }
+ }
+
+ /// <summary>One text:p per line; runs of spaces and tabs as text:s and text:tab, which XML would collapse.</summary>
+ private static void Paragraphs(StringBuilder sb, string text)
+ {
+ foreach (var line in text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'))
+ {
+ sb.Append("<text:p>");
+ for (var i = 0; i < line.Length; i++)
+ {
+ var ch = line[i];
+ if (ch == ' ')
+ {
+ var run = 1;
+ while (i + run < line.Length && line[i + run] == ' ')
+ run++;
+ // The first space of a run is kept as text unless the line starts with it.
+ var extra = i == 0 ? run : run - 1;
+ if (i > 0)
+ sb.Append(' ');
+ if (extra > 0)
+ sb.Append(extra == 1 ? "<text:s/>" : string.Create(CultureInfo.InvariantCulture, $"<text:s text:c=\"{extra}\"/>"));
+ i += run - 1;
+ }
+ else if (ch == '\t')
+ sb.Append("<text:tab/>");
+ else if (ch >= ' ')
+ sb.Append(Escape(ch.ToString()));
+ }
+ sb.Append("</text:p>");
+ }
+ }
+
+ private static string Repeated(string what, int count) =>
+ count > 1 ? string.Create(CultureInfo.InvariantCulture, $" table:number-{what}-repeated=\"{count}\"") : "";
+
+ private static string Settings(List<(string Name, int FrozenRows)> frozen)
+ {
+ var sb = new StringBuilder(Declaration);
+ sb.Append(CultureInfo.InvariantCulture, $"<office:document-settings xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" xmlns:config=\"urn:oasis:names:tc:opendocument:xmlns:config:1.0\" office:version=\"{Version}\">");
+ sb.Append("<office:settings><config:config-item-set config:name=\"ooo:view-settings\"><config:config-item-map-indexed config:name=\"Views\"><config:config-item-map-entry>");
+ sb.Append("<config:config-item config:name=\"ViewId\" config:type=\"string\">view1</config:config-item><config:config-item-map-named config:name=\"Tables\">");
+ foreach (var (name, rows) in frozen)
+ {
+ sb.Append(CultureInfo.InvariantCulture, $"<config:config-item-map-entry config:name=\"{Escape(name)}\">");
+ void Item(string item, string type, int value) =>
+ sb.Append(CultureInfo.InvariantCulture, $"<config:config-item config:name=\"{item}\" config:type=\"{type}\">{value}</config:config-item>");
+ Item("HorizontalSplitMode", "short", 0);
+ Item("VerticalSplitMode", "short", 2);
+ Item("HorizontalSplitPosition", "int", 0);
+ Item("VerticalSplitPosition", "int", rows);
+ Item("ActiveSplitRange", "short", 2);
+ Item("PositionLeft", "int", 0);
+ Item("PositionRight", "int", 0);
+ Item("PositionTop", "int", 0);
+ Item("PositionBottom", "int", rows);
+ sb.Append("</config:config-item-map-entry>");
+ }
+ sb.Append("</config:config-item-map-named></config:config-item-map-entry></config:config-item-map-indexed></config:config-item-set></office:settings></office:document-settings>");
+ return sb.ToString();
+ }
+
+ private static string Escape(string text) =>
+ SecurityElement.Escape(new string([.. text.Where(ch => ch is '\t' or '\n' or '\r' || ch >= ' ')])) ?? "";
+
+ private static void Add(ZipArchive zip, string name, string content, CompressionLevel level = CompressionLevel.Optimal)
+ {
+ using var writer = new StreamWriter(zip.CreateEntry(name, level).Open(), new UTF8Encoding(false));
+ writer.Write(content);
+ }
+
+ /// <summary>office:automatic-styles of content.xml: one style per distinct column width, row height, cell look and number format.</summary>
+ private sealed class AutomaticStyles
+ {
+ private readonly StringBuilder _columns = new();
+ private readonly StringBuilder _rows = new();
+ private readonly StringBuilder _data = new();
+ private readonly StringBuilder _cells = new();
+ private readonly Dictionary<double, string> _columnNames = [];
+ private readonly Dictionary<double, string> _rowNames = [];
+ private readonly Dictionary<string, (string? Name, string ValueType)> _dataNames = [];
+ private readonly Dictionary<(CellStyle, string?), string?> _cellNames = [];
+
+ public string Table() => "ta1";
+
+ public string Column(double width)
+ {
+ if (!_columnNames.TryGetValue(width, out var name))
+ {
+ _columnNames[width] = name = "co" + (_columnNames.Count + 1).ToString(CultureInfo.InvariantCulture);
+ _columns.Append(CultureInfo.InvariantCulture,
+ $"<style:style style:name=\"{name}\" style:family=\"table-column\"><style:table-column-properties fo:break-before=\"auto\" style:column-width=\"{width * OdsReader.PointsPerCharacter:0.###}pt\"/></style:style>");
+ }
+ return name;
+ }
+
+ /// <summary>A row style: a custom height, or (null) the height that fits the content.</summary>
+ public string Row(double? height)
+ {
+ var key = height ?? -1;
+ if (!_rowNames.TryGetValue(key, out var name))
+ {
+ _rowNames[key] = name = "ro" + (_rowNames.Count + 1).ToString(CultureInfo.InvariantCulture);
+ _rows.Append(CultureInfo.InvariantCulture,
+ $"<style:style style:name=\"{name}\" style:family=\"table-row\"><style:table-row-properties style:row-height=\"{height ?? 15:0.##}pt\" fo:break-before=\"auto\" style:use-optimal-row-height=\"{(height is null ? "true" : "false")}\"/></style:style>");
+ }
+ return name;
+ }
+
+ /// <summary>The data style of an Excel format code (null name = General) and the value type of its cells.</summary>
+ public (string? Name, string ValueType) DataStyle(string? format)
+ {
+ if (format is null)
+ return (null, "float");
+ if (!_dataNames.TryGetValue(format, out var result))
+ {
+ var name = "N" + (_dataNames.Count + 1).ToString(CultureInfo.InvariantCulture);
+ if (OdsNumberStyles.ToOdf(format, name) is var (xml, valueType))
+ {
+ _data.Append(xml);
+ result = (name, valueType);
+ }
+ else
+ {
+ result = (null, "float");
+ }
+ _dataNames[format] = result;
+ }
+ return result;
+ }
+
+ /// <summary>The cell style for a look and data style; null for the default look without a number format.</summary>
+ public string? Cell(CellStyle style, string? dataStyle)
+ {
+ if (style == CellStyle.Default && dataStyle is null)
+ return null;
+ if (_cellNames.TryGetValue((style, dataStyle), out var name))
+ return name;
+ name = "ce" + (_cellNames.Count + 1).ToString(CultureInfo.InvariantCulture);
+ _cellNames[(style, dataStyle)] = name;
+
+ _cells.Append(CultureInfo.InvariantCulture, $"<style:style style:name=\"{name}\" style:family=\"table-cell\" style:parent-style-name=\"Default\"");
+ if (dataStyle is not null)
+ _cells.Append(CultureInfo.InvariantCulture, $" style:data-style-name=\"{dataStyle}\"");
+ _cells.Append("><style:table-cell-properties");
+ if (style.Fill is { } fill)
+ _cells.Append(CultureInfo.InvariantCulture, $" fo:background-color=\"{fill}\"");
+ if (style.Left == style.Right && style.Left == style.Top && style.Left == style.Bottom)
+ {
+ if (style.Left.IsVisible)
+ _cells.Append(CultureInfo.InvariantCulture, $" fo:border=\"{Border(style.Left)}\"");
+ }
+ else
+ {
+ foreach (var (side, border) in new[] { ("left", style.Left), ("right", style.Right), ("top", style.Top), ("bottom", style.Bottom) })
+ _cells.Append(CultureInfo.InvariantCulture, $" fo:border-{side}=\"{(border.IsVisible ? Border(border) : "none")}\"");
+ }
+ if (style.VerticalAlign != CellVerticalAlign.Bottom)
+ _cells.Append(CultureInfo.InvariantCulture, $" style:vertical-align=\"{(style.VerticalAlign == CellVerticalAlign.Top ? "top" : "middle")}\"");
+ if (style.Wrap)
+ _cells.Append(" fo:wrap-option=\"wrap\"");
+ if (style.Align != CellAlign.General)
+ _cells.Append(" style:text-align-source=\"fix\" style:repeat-content=\"false\"");
+ _cells.Append("/>");
+ if (style.Align != CellAlign.General)
+ {
+ var align = style.Align switch { CellAlign.Left => "start", CellAlign.Center => "center", _ => "end" };
+ _cells.Append(CultureInfo.InvariantCulture, $"<style:paragraph-properties fo:text-align=\"{align}\"/>");
+ }
+
+ var text = new StringBuilder();
+ if (style.Bold)
+ text.Append(" fo:font-weight=\"bold\" style:font-weight-asian=\"bold\" style:font-weight-complex=\"bold\"");
+ if (style.Italic)
+ text.Append(" fo:font-style=\"italic\" style:font-style-asian=\"italic\" style:font-style-complex=\"italic\"");
+ if (style.Underline)
+ text.Append(" style:text-underline-style=\"solid\" style:text-underline-width=\"auto\" style:text-underline-color=\"font-color\"");
+ if (style.Strike)
+ text.Append(" style:text-line-through-style=\"solid\" style:text-line-through-type=\"single\"");
+ if (style.FontSize is { } size)
+ text.Append(CultureInfo.InvariantCulture, $" fo:font-size=\"{size:0.##}pt\" style:font-size-asian=\"{size:0.##}pt\" style:font-size-complex=\"{size:0.##}pt\"");
+ if (style.Color is { } color)
+ text.Append(CultureInfo.InvariantCulture, $" fo:color=\"{color}\"");
+ if (text.Length > 0)
+ _cells.Append("<style:text-properties").Append(text).Append("/>");
+ _cells.Append("</style:style>");
+ return name;
+ }
+
+ public string Xml() =>
+ _columns.ToString() + _rows +
+ "<style:style style:name=\"ta1\" style:family=\"table\"><style:table-properties table:display=\"true\" style:writing-mode=\"lr-tb\"/></style:style>" +
+ _data + _cells;
+
+ /// <summary>An Excel border as an ODF border: widths LibreOffice uses when it imports the same Excel style.</summary>
+ private static string Border(CellBorder border)
+ {
+ var (width, pattern) = border.Style switch
+ {
+ "hair" => (0.1, "solid"),
+ "medium" => (1.75, "solid"),
+ "thick" => (2.5, "solid"),
+ "double" => (2.25, "double"),
+ "dotted" => (0.75, "dotted"),
+ "dashed" => (0.75, "dashed"),
+ "mediumDashed" => (1.75, "dashed"),
+ "dashDot" => (0.75, "dot-dash"),
+ "mediumDashDot" or "slantDashDot" => (1.75, "dot-dash"),
+ "dashDotDot" => (0.75, "dot-dot-dash"),
+ "mediumDashDotDot" => (1.75, "dot-dot-dash"),
+ _ => (0.75, "solid"),
+ };
+ return string.Create(CultureInfo.InvariantCulture, $"{width}pt {pattern} {border.Color ?? "#000000"}");
+ }
+ }
+}
diff --git a/src/Filee.Engines/Office/Sheets/Workbook.cs b/src/Filee.Engines/Office/Sheets/Workbook.cs
index 07a25b43..30fbae36 100644
--- a/src/Filee.Engines/Office/Sheets/Workbook.cs
+++ b/src/Filee.Engines/Office/Sheets/Workbook.cs
@@ -1,5 +1,6 @@
-// In-memory spreadsheet between the readers (XLSX, CSV) and the writers (CSV, XLSX, HWPX tables).
-// Cells hold the text as the spreadsheet shows it (numbers and dates already formatted).
+// In-memory spreadsheet between the readers (XLSX, XLS, ODS, CSV/TSV) and the writers (XLSX, ODS, CSV/TSV, HWPX
+// tables). Cells hold the text as the spreadsheet shows it (numbers and dates already formatted) plus, for numbers,
+// the value and its number format, so spreadsheet → spreadsheet conversions keep real numbers.
namespace Filee.Engines.Office.Sheets;
@@ -163,5 +164,17 @@ internal sealed record CellStyle
/// <param name="IsNumber">Numbers (and dates) align right under the General alignment.</param>
internal sealed record SheetCell(string Text, CellStyle Style, bool IsNumber = false)
{
+ /// <summary>
+ /// The value behind <see cref="Text"/>: numbers, dates and times as Excel serial days (1900 date system) and
+ /// booleans as 1 / 0; null for text and errors. Writers store it instead of the text.
+ /// </summary>
+ public double? Value { get; init; }
+
+ /// <summary>Excel number format code of <see cref="Value"/> ("#,##0", "yyyy-mm-dd"); null = General.</summary>
+ public string? NumberFormat { get; init; }
+
+ /// <summary>A TRUE / FALSE cell (<see cref="Value"/> is 1 or 0).</summary>
+ public bool IsBoolean { get; init; }
+
public bool HasContent => Text.Length > 0 || Style.Fill is not null || Style.HasBorders;
}
diff --git a/src/Filee.Engines/Office/Sheets/XlsLayout.cs b/src/Filee.Engines/Office/Sheets/XlsLayout.cs
new file mode 100644
index 00000000..e0d119ad
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/XlsLayout.cs
@@ -0,0 +1,177 @@
+// Column widths and row heights of an XLS file, read from the BIFF records themselves. ExcelDataReader only reports
+// widths whose "set by the user" flag is on (LibreOffice never sets it) and every row's height without telling
+// custom from automatic ones; Excel uses the COLINFO width and the ROW "unsynced" flag, so this reads those.
+// Encrypted workbooks and pre-Excel 5 files return null: the reader then falls back to ExcelDataReader's values.
+
+using System.Buffers.Binary;
+using System.Text;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal static class XlsLayout
+{
+ /// <summary>Columns and rows of one worksheet that differ from the defaults.</summary>
+ /// <param name="Columns">Width in characters (as XLSX stores it) and hidden flag, by 0-based column.</param>
+ /// <param name="Rows">Height in points, whether it is a custom height, and hidden flag, by 0-based row.</param>
+ public sealed record Sheet(Dictionary<int, (double Width, bool Hidden)> Columns, Dictionary<int, (double Points, bool Custom, bool Hidden)> Rows);
+
+ private const int MaxColumn = 16_383;
+
+ /// <summary>The layout of every worksheet in workbook order (chart sheets left out, like ExcelDataReader).</summary>
+ public static List<Sheet>? Read(string path)
+ {
+ try
+ {
+ return WorkbookStream(File.ReadAllBytes(path)) is { } workbook ? Parse(workbook) : null;
+ }
+ catch (Exception ex) when (ex is ArgumentException or IndexOutOfRangeException or InvalidDataException or IOException or OverflowException)
+ {
+ return null;
+ }
+ }
+
+ // ───────────────────────── BIFF records ─────────────────────────
+
+ private static List<Sheet>? Parse(byte[] stream)
+ {
+ var offsets = new List<int>();
+ foreach (var (id, data) in Records(stream, 0))
+ {
+ switch (id)
+ {
+ case 0x002F: // FILEPASS: everything after it is encrypted
+ return null;
+ case 0x0085 when data.Length >= 6 && data[5] == 0: // BOUNDSHEET of a worksheet
+ offsets.Add(BinaryPrimitives.ReadInt32LittleEndian(data));
+ break;
+ }
+ }
+
+ var sheets = new List<Sheet>();
+ foreach (var offset in offsets)
+ {
+ var sheet = new Sheet([], []);
+ foreach (var (id, data) in Records(stream, offset))
+ {
+ if (id == 0x007D && data.Length >= 10) // COLINFO
+ {
+ var first = BinaryPrimitives.ReadUInt16LittleEndian(data);
+ var last = Math.Min((int)BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(2)), MaxColumn);
+ var width = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(4)) / 256.0;
+ var hidden = (data[8] & 0x01) != 0 || width == 0;
+ for (var c = first; c <= last; c++)
+ sheet.Columns[c] = (width, hidden);
+ }
+ else if (id == 0x0208 && data.Length >= 14) // ROW
+ {
+ var height = (BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(6)) & 0x7FFF) / 20.0;
+ var flags = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(12));
+ sheet.Rows[BinaryPrimitives.ReadUInt16LittleEndian(data)] = (height, (flags & 0x40) != 0, (flags & 0x20) != 0);
+ }
+ }
+ sheets.Add(sheet);
+ }
+ return sheets;
+ }
+
+ /// <summary>The records of one substream: from its BOF up to its EOF (or the next BOF).</summary>
+ private static IEnumerable<(int Id, byte[] Data)> Records(byte[] stream, int offset)
+ {
+ if (offset < 0 || offset + 4 > stream.Length || BinaryPrimitives.ReadUInt16LittleEndian(stream.AsSpan(offset)) != 0x0809)
+ yield break;
+ var position = offset;
+ var first = true;
+ while (position + 4 <= stream.Length)
+ {
+ var id = BinaryPrimitives.ReadUInt16LittleEndian(stream.AsSpan(position));
+ var length = BinaryPrimitives.ReadUInt16LittleEndian(stream.AsSpan(position + 2));
+ if (id == 0x000A || id == 0x0809 && !first || position + 4 + length > stream.Length)
+ yield break;
+ yield return (id, stream.AsSpan(position + 4, length).ToArray());
+ position += 4 + length;
+ first = false;
+ }
+ }
+
+ // ───────────────────────── Compound file ─────────────────────────
+
+ private const uint LastSector = 0xFFFFFFFA; // sector numbers at and above are markers (end of chain, free, ...)
+
+ /// <summary>The "Workbook" (Excel 97+) or "Book" (Excel 5/95) stream of a compound file; null if there is none.</summary>
+ private static byte[]? WorkbookStream(byte[] file)
+ {
+ if (file.Length < 512 || BinaryPrimitives.ReadUInt64LittleEndian(file) != 0xE11AB1A1E011CFD0)
+ return null;
+ var sectorSize = 1 << BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(30));
+ var miniSectorSize = 1 << BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(32));
+ if (sectorSize is not (512 or 4096) || miniSectorSize > sectorSize)
+ return null;
+ var sectorCount = (file.Length + sectorSize - 1) / sectorSize;
+ ArraySegment<byte> Sector(uint index)
+ {
+ var start = (int)Math.Min((long)(index + 1) * sectorSize, file.Length);
+ return new ArraySegment<byte>(file, start, Math.Min(sectorSize, file.Length - start));
+ }
+
+ // The FAT is listed by the header (109 sectors) and, in big files, a chain of DIFAT sectors.
+ var fatSectors = new List<uint>();
+ for (var i = 0; i < 109; i++)
+ fatSectors.Add(BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(76 + i * 4)));
+ for (var difat = BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(68)); difat < LastSector && fatSectors.Count < sectorCount * 2;)
+ {
+ var sector = Sector(difat);
+ if (sector.Count < sectorSize)
+ break;
+ for (var i = 0; i + 4 < sector.Count; i += 4)
+ fatSectors.Add(BinaryPrimitives.ReadUInt32LittleEndian(sector.AsSpan(i)));
+ difat = BinaryPrimitives.ReadUInt32LittleEndian(sector.AsSpan(sector.Count - 4));
+ }
+ var fat = new List<uint>();
+ foreach (var sector in fatSectors.Where(s => s < LastSector))
+ {
+ var data = Sector(sector);
+ for (var i = 0; i + 4 <= data.Count; i += 4)
+ fat.Add(BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(i)));
+ }
+
+ // A stream's sectors, each pointing to the next one in the table; the step count stops broken, circular chains.
+ byte[] Chain(uint start, List<uint> table, Func<uint, ArraySegment<byte>> read)
+ {
+ var bytes = new List<byte>();
+ for (uint s = start, steps = 0; s < LastSector && s < table.Count && steps <= table.Count; s = table[(int)s], steps++)
+ bytes.AddRange(read(s));
+ return [.. bytes];
+ }
+
+ var directory = Chain(BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(48)), fat, Sector);
+ (uint Start, long Size)? workbook = null;
+ for (var i = 0; i + 128 <= directory.Length && workbook is null; i += 128)
+ {
+ var entry = directory.AsSpan(i, 128);
+ var nameLength = Math.Clamp((int)BinaryPrimitives.ReadUInt16LittleEndian(entry[64..]) - 2, 0, 62);
+ var name = Encoding.Unicode.GetString(entry[..nameLength]);
+ if (entry[66] == 2 && (name.Equals("Workbook", StringComparison.OrdinalIgnoreCase) || name.Equals("Book", StringComparison.OrdinalIgnoreCase)))
+ workbook = (BinaryPrimitives.ReadUInt32LittleEndian(entry[116..]), BinaryPrimitives.ReadUInt32LittleEndian(entry[120..]));
+ }
+ if (workbook is not { } stream || directory.Length < 128)
+ return null;
+
+ byte[] bytes;
+ if (stream.Size < BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(56)))
+ {
+ // Small streams live in the mini stream (held by the root entry), addressed through the mini FAT.
+ var miniStream = Chain(BinaryPrimitives.ReadUInt32LittleEndian(directory.AsSpan(116)), fat, Sector);
+ var miniFatBytes = Chain(BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(60)), fat, Sector);
+ var miniFat = new List<uint>();
+ for (var i = 0; i + 4 <= miniFatBytes.Length; i += 4)
+ miniFat.Add(BinaryPrimitives.ReadUInt32LittleEndian(miniFatBytes.AsSpan(i)));
+ bytes = Chain(stream.Start, miniFat, s =>
+ (long)(s + 1) * miniSectorSize <= miniStream.Length ? new ArraySegment<byte>(miniStream, (int)s * miniSectorSize, miniSectorSize) : []);
+ }
+ else
+ {
+ bytes = Chain(stream.Start, fat, Sector);
+ }
+ return bytes.Length >= stream.Size ? bytes[..(int)stream.Size] : null;
+ }
+}
diff --git a/src/Filee.Engines/Office/Sheets/XlsReader.cs b/src/Filee.Engines/Office/Sheets/XlsReader.cs
new file mode 100644
index 00000000..6cf7949a
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/XlsReader.cs
@@ -0,0 +1,200 @@
+// XLS (Excel 97–2003, BIFF8, also .xlt and the older BIFF2–5) → Workbook without Excel or LibreOffice: the binary
+// records are read by ExcelDataReader (MIT), values are formatted with the same number formats as XLSX
+// (NumberFormatter), plus merged cells, column widths, row heights, hidden rows / columns / sheets and alignment.
+// ExcelDataReader exposes no fonts, fills or borders, so XLS cells keep the default look; widths and heights come
+// from the BIFF records themselves (XlsLayout).
+
+using System.Text;
+using ExcelDataReader;
+using ExcelDataReader.Exceptions;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal static class XlsReader
+{
+ /// <summary>Reads every visible sheet of <paramref name="path"/>.</summary>
+ public static Workbook Read(string path)
+ {
+ // Web apps often save XLSX with an .xls name; the XLSX reader keeps more of such files (fonts, fills).
+ if (StartsWith(path, "PK"u8))
+ return XlsxReader.Read(path);
+
+ // BIFF5 and older store text in the workbook's ANSI code page (cp1252, cp949, ...).
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ try
+ {
+ using var stream = File.OpenRead(path);
+ using var reader = ExcelReaderFactory.CreateReader(stream);
+ var formatter = new NumberFormatter(); // ExcelDataReader already turns 1904-based dates into DateTime
+ var layouts = XlsLayout.Read(path);
+ var book = new Workbook();
+ var index = 0;
+ do
+ {
+ if (reader.VisibleState is null or "visible")
+ book.Sheets.Add(ReadSheet(reader, formatter, layouts?.ElementAtOrDefault(index)));
+ index++;
+ }
+ while (reader.NextResult());
+ return book;
+ }
+ catch (InvalidPasswordException)
+ {
+ throw new InvalidDataException("The workbook is protected with a password (encrypted). Remove the password in Excel and convert it again.");
+ }
+ catch (HeaderException)
+ {
+ throw new InvalidDataException(StartsWith(path, "<"u8) || StartsWith(path, [0xEF, 0xBB, 0xBF, (byte)'<'])
+ ? "The file is not an Excel 97–2003 workbook but a web page or XML file saved with an .xls name. Open it in Excel and save it as XLSX."
+ : "The file is not an Excel 97–2003 workbook.");
+ }
+ catch (Exception ex) when (ex is ExcelReaderException or NotSupportedException or EndOfStreamException)
+ {
+ throw new InvalidDataException("The Excel 97–2003 workbook could not be read: " + ex.Message, ex);
+ }
+ }
+
+ /// <param name="layout">Widths and heights from the BIFF records; null to use what ExcelDataReader reports.</param>
+ private static Worksheet ReadSheet(IExcelDataReader reader, NumberFormatter formatter, XlsLayout.Sheet? layout)
+ {
+ var sheet = new Worksheet(string.IsNullOrEmpty(reader.Name) ? "Sheet" : reader.Name);
+ var heights = new Dictionary<int, double>();
+ var row = -1;
+ while (reader.Read())
+ {
+ row++;
+ heights[row] = reader.RowHeight;
+ for (var c = 0; c < reader.FieldCount; c++)
+ {
+ if (Cell(reader, c, formatter) is { HasContent: true } cell)
+ sheet.Set(row, c, cell);
+ }
+ }
+
+ if (layout is not null)
+ {
+ foreach (var (c, (width, hidden)) in layout.Columns)
+ {
+ if (hidden)
+ sheet.HiddenColumns.Add(c);
+ else
+ sheet.ColumnWidths[c] = width;
+ }
+ foreach (var (r, (points, custom, hidden)) in layout.Rows)
+ {
+ if (hidden)
+ sheet.HiddenRows.Add(r);
+ else if (custom)
+ sheet.RowHeights[r] = points;
+ }
+ }
+ else
+ {
+ // ExcelDataReader reports hidden rows with height 0 and every other row's height, custom or not: keep
+ // the heights unlike the sheet's usual row height.
+ var usual = heights.Values.Where(h => h > 0).GroupBy(h => h).MaxBy(g => g.Count())?.Key;
+ foreach (var (r, height) in heights)
+ {
+ if (height <= 0)
+ sheet.HiddenRows.Add(r);
+ else if (height != usual)
+ sheet.RowHeights[r] = height;
+ }
+ // Hidden columns report width 0; columns without a width report Excel's standard width.
+ for (var c = 0; c < reader.FieldCount; c++)
+ {
+ var width = reader.GetColumnWidth(c);
+ if (width <= 0)
+ sheet.HiddenColumns.Add(c);
+ else if (Math.Abs(width - Worksheet.StandardColumnWidth) > 0.005)
+ sheet.ColumnWidths[c] = width;
+ }
+ }
+
+ foreach (var merge in reader.MergeCells ?? [])
+ {
+ if (merge.ToRow > merge.FromRow || merge.ToColumn > merge.FromColumn)
+ sheet.Merges.Add(new CellRange(merge.FromRow, merge.FromColumn, merge.ToRow, merge.ToColumn));
+ }
+ return sheet;
+ }
+
+ private static SheetCell? Cell(IExcelDataReader reader, int column, NumberFormatter formatter)
+ {
+ var value = reader.GetValue(column);
+ var style = Style(reader.GetCellStyle(column));
+ if (reader.GetCellError(column) is { } error)
+ return new SheetCell(ErrorText(error), style);
+
+ double number;
+ switch (value)
+ {
+ case null:
+ return null; // blank cells: their fills and borders are not available
+ case string text:
+ return new SheetCell(text, style);
+ case bool on:
+ return new SheetCell(on ? "TRUE" : "FALSE", style) { Value = on ? 1 : 0, IsBoolean = true };
+ case DateTime date:
+ number = NumberFormatter.ToSerial(date);
+ break;
+ case TimeSpan duration:
+ number = duration.TotalDays;
+ break;
+ default:
+ number = Convert.ToDouble(value, System.Globalization.CultureInfo.InvariantCulture);
+ break;
+ }
+
+ // Built-in formats the XLSX reader knows (dates in ISO order) look the same from XLS; ExcelDataReader's
+ // string is used for the workbook's own formats and localized built-ins.
+ var index = reader.GetNumberFormatIndex(column);
+ var format = NumberFormatter.BuiltInFormats.TryGetValue(index, out var builtIn) ? builtIn : reader.GetNumberFormatString(column);
+ return new SheetCell(formatter.Format(number, format), style, IsNumber: true)
+ {
+ Value = number,
+ NumberFormat = NumberFormatter.IsGeneral(format) ? null : format,
+ };
+ }
+
+ private static CellStyle Style(ExcelDataReader.CellStyle? style)
+ {
+ if (style is null)
+ return CellStyle.Default;
+ var align = style.HorizontalAlignment switch
+ {
+ HorizontalAlignment.Left or HorizontalAlignment.Filled or HorizontalAlignment.Justified or HorizontalAlignment.Distributed => CellAlign.Left,
+ HorizontalAlignment.Center or HorizontalAlignment.Centered or HorizontalAlignment.CenteredAcrossSelection => CellAlign.Center,
+ HorizontalAlignment.Right => CellAlign.Right,
+ _ => CellAlign.General,
+ };
+ var vertical = style.VerticalAlignment switch
+ {
+ VerticalAlignment.Top => CellVerticalAlign.Top,
+ VerticalAlignment.Center or VerticalAlignment.Justify or VerticalAlignment.Distributed => CellVerticalAlign.Center,
+ _ => CellVerticalAlign.Bottom,
+ };
+ return align == CellAlign.General && vertical == CellVerticalAlign.Bottom
+ ? CellStyle.Default
+ : CellStyle.Default with { Align = align, VerticalAlign = vertical };
+ }
+
+ private static string ErrorText(CellError error) => error switch
+ {
+ CellError.NULL => "#NULL!",
+ CellError.DIV0 => "#DIV/0!",
+ CellError.VALUE => "#VALUE!",
+ CellError.REF => "#REF!",
+ CellError.NAME => "#NAME?",
+ CellError.NUM => "#NUM!",
+ CellError.NA => "#N/A",
+ _ => "#GETTING_DATA",
+ };
+
+ private static bool StartsWith(string path, ReadOnlySpan<byte> signature)
+ {
+ Span<byte> head = stackalloc byte[signature.Length];
+ using var stream = File.OpenRead(path);
+ return stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false) == head.Length && head.SequenceEqual(signature);
+ }
+}
diff --git a/src/Filee.Engines/Office/Sheets/XlsxReader.cs b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
index 68334dd6..dbb12776 100644
--- a/src/Filee.Engines/Office/Sheets/XlsxReader.cs
+++ b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
@@ -6,7 +6,6 @@
using System.Globalization;
using System.Text;
using System.Xml.Linq;
-using ExcelNumberFormat;
using Filee.Engines.Office.Ooxml;
namespace Filee.Engines.Office.Sheets;
@@ -16,43 +15,13 @@ internal sealed class XlsxReader
private static readonly XNamespace S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
private static readonly XNamespace R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
- /// <summary>Built-in number formats (ECMA-376 18.8.30); 14 uses the ISO date order most locales read.</summary>
- private static readonly Dictionary<int, string> BuiltInFormats = new()
- {
- [0] = "General",
- [1] = "0",
- [2] = "0.00",
- [3] = "#,##0",
- [4] = "#,##0.00",
- [9] = "0%",
- [10] = "0.00%",
- [11] = "0.00E+00",
- [12] = "# ?/?",
- [13] = "# ??/??",
- [14] = "yyyy-mm-dd",
- [15] = "d-mmm-yy",
- [16] = "d-mmm",
- [17] = "mmm-yy",
- [18] = "h:mm AM/PM",
- [19] = "h:mm:ss AM/PM",
- [20] = "h:mm",
- [21] = "h:mm:ss",
- [22] = "yyyy-mm-dd h:mm",
- [37] = "#,##0 ;(#,##0)",
- [38] = "#,##0 ;[Red](#,##0)",
- [39] = "#,##0.00;(#,##0.00)",
- [40] = "#,##0.00;[Red](#,##0.00)",
- [45] = "mm:ss",
- [46] = "[h]:mm:ss",
- [47] = "mmss.0",
- [48] = "##0.0E+0",
- [49] = "@",
- };
+ /// <summary>Days between the 1900 and 1904 date systems (1 January 1904 is serial 1462 in the 1900 system).</summary>
+ private const double Date1904Offset = 1462;
private readonly OpcPackage _package;
private readonly List<string> _sharedStrings = [];
private readonly List<(CellStyle Style, string Format)> _cellFormats = [];
- private readonly Dictionary<string, NumberFormat> _numberFormats = [];
+ private NumberFormatter _formatter = new();
private bool _date1904;
private XlsxReader(OpcPackage package) => _package = package;
@@ -69,6 +38,7 @@ internal sealed class XlsxReader
var workbookPath = _package.MainPartPath ?? "xl/workbook.xml";
var workbook = _package.Part(workbookPath)?.Root ?? throw new InvalidDataException("The file is not an Excel workbook (no xl/workbook.xml).");
_date1904 = (string?)workbook.Element(S + "workbookPr")?.Attribute("date1904") is "1" or "true";
+ _formatter = new NumberFormatter(_date1904);
var colors = OoxmlColors.FromTheme(_package.TargetOfType(workbookPath, "/theme") is { } theme ? _package.Part(theme) : null);
if (_package.TargetOfType(workbookPath, "/sharedStrings") is { } shared)
@@ -180,7 +150,7 @@ internal sealed class XlsxReader
Bottom = border.Item4,
};
var formatId = Index(xf, "numFmtId");
- _cellFormats.Add((style, formats.GetValueOrDefault(formatId) ?? BuiltInFormats.GetValueOrDefault(formatId, "General")));
+ _cellFormats.Add((style, formats.GetValueOrDefault(formatId) ?? NumberFormatter.BuiltInFormats.GetValueOrDefault(formatId, "General")));
}
}
@@ -237,8 +207,7 @@ internal sealed class XlsxReader
var c = CellRange.TryParseCell((string?)cell.Attribute("r") ?? "", out _, out var column) ? column : nextColumn;
nextColumn = c + 1;
var (style, format) = Index(cell, "s") is var s && s < _cellFormats.Count ? _cellFormats[s] : (CellStyle.Default, "General");
- var (text, isNumber) = Value(cell, format);
- var value = new SheetCell(text, style, isNumber);
+ var value = Value(cell, style, format);
if (value.HasContent)
sheet.Set(r, c, value);
}
@@ -250,57 +219,41 @@ internal sealed class XlsxReader
return sheet;
}
- /// <summary>The displayed text of a cell and whether it is a number (dates included).</summary>
- private (string Text, bool IsNumber) Value(XElement cell, string format)
+ /// <summary>
+ /// The displayed text of a cell, and for numbers (dates included) and booleans the value behind it. Dates in a
+ /// 1904-based workbook are moved to the 1900 date system, so the value means the same in every workbook.
+ /// </summary>
+ private SheetCell Value(XElement cell, CellStyle style, string format)
{
var type = (string?)cell.Attribute("t") ?? "n";
var raw = cell.Element(S + "v")?.Value;
switch (type)
{
case "s":
- return (int.TryParse(raw, out var index) && index >= 0 && index < _sharedStrings.Count ? _sharedStrings[index] : "", false);
+ return new SheetCell(int.TryParse(raw, out var index) && index >= 0 && index < _sharedStrings.Count ? _sharedStrings[index] : "", style);
case "inlineStr":
- return (cell.Element(S + "is") is { } inline ? RichText(inline) : raw ?? "", false);
+ return new SheetCell(cell.Element(S + "is") is { } inline ? RichText(inline) : raw ?? "", style);
case "str":
case "e":
- return (raw ?? "", false);
+ return new SheetCell(raw ?? "", style);
case "b":
- return (raw is "1" or "true" ? "TRUE" : "FALSE", false);
+ var on = raw is "1" or "true";
+ return new SheetCell(on ? "TRUE" : "FALSE", style) { Value = on ? 1 : 0, IsBoolean = true };
case "d":
return DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
- ? (Format(date.ToOADate(), format), true)
- : (raw ?? "", false);
+ ? Number(NumberFormatter.ToSerial(date) - (_date1904 ? Date1904Offset : 0), style, format)
+ : new SheetCell(raw ?? "", style);
default:
return double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
- ? (Format(number, format), true)
- : (raw ?? "", false);
+ ? Number(number, style, format)
+ : new SheetCell(raw ?? "", style);
}
}
- private string Format(double value, string format)
+ /// <param name="value">The stored number, in the workbook's own date system.</param>
+ private SheetCell Number(double value, CellStyle style, string format) => new(_formatter.Format(value, format), style, IsNumber: true)
{
- if (format is "General" or "" || format.Equals("general", StringComparison.OrdinalIgnoreCase))
- return General(value);
- if (!_numberFormats.TryGetValue(format, out var parsed))
- _numberFormats[format] = parsed = new NumberFormat(format);
- if (!parsed.IsValid)
- return General(value);
- try
- {
- return parsed.Format(value, CultureInfo.InvariantCulture, _date1904);
- }
- catch (Exception ex) when (ex is ArgumentException or FormatException or OverflowException)
- {
- return General(value);
- }
- }
-
- /// <summary>Excel's General format: up to 11 significant characters, no trailing zeros.</summary>
- internal static string General(double value)
- {
- if (value == Math.Floor(value) && Math.Abs(value) < 1e11)
- return value.ToString("0", CultureInfo.InvariantCulture);
- var text = value.ToString("G10", CultureInfo.InvariantCulture);
- return text.Contains('E') ? value.ToString("0.#####E+00", CultureInfo.InvariantCulture) : text;
- }
+ Value = _date1904 && _formatter.IsDate(format) ? value + Date1904Offset : value,
+ NumberFormat = NumberFormatter.IsGeneral(format) ? null : format,
+ };
}
diff --git a/src/Filee.Engines/Office/Sheets/XlsxWriter.cs b/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
index a1402fbc..c8fba27c 100644
--- a/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
+++ b/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
@@ -1,5 +1,7 @@
-// Worksheet → minimal XLSX package (one sheet, values only): numbers as numbers, everything else as inline strings,
-// column widths from the sheet. Used for CSV → XLSX; opens in Excel, LibreOffice and Google Sheets.
+// Workbook → XLSX package: every sheet, numbers and dates as numbers with their number formats, booleans, text as
+// inline strings, fonts / fills / borders / alignment, merged cells, column widths, row heights, hidden rows and
+// columns, and frozen header rows. Used for CSV, TSV, XLS and ODS → XLSX; opens in Excel, LibreOffice and Google
+// Sheets.
using System.Globalization;
using System.IO.Compression;
@@ -10,61 +12,128 @@ namespace Filee.Engines.Office.Sheets;
internal static class XlsxWriter
{
- public static void Write(Worksheet sheet, string path)
+ private const string Main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
+ private const string RelationshipsNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+
+ /// <summary>Built-in format ids Excel knows without a numFmt element (ECMA-376 18.8.30, locale independent ones).</summary>
+ private static readonly Dictionary<string, int> BuiltInIds = new()
+ {
+ ["0"] = 1,
+ ["0.00"] = 2,
+ ["#,##0"] = 3,
+ ["#,##0.00"] = 4,
+ ["0%"] = 9,
+ ["0.00%"] = 10,
+ ["0.00E+00"] = 11,
+ ["@"] = 49,
+ };
+
+ public static void Write(Workbook book, string path)
{
+ var sheets = book.Sheets.Count > 0 ? book.Sheets : [new Worksheet("Sheet1")];
+ var names = UniqueNames(sheets.Select(s => s.Name));
+ var styles = new StyleTable();
+ var sheetXml = sheets.Select((s, i) => SheetXml(s, styles, selected: i == 0)).ToList();
+
using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
- Add(zip, "[Content_Types].xml", """
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>
- """);
+ Add(zip, "[Content_Types].xml",
+ """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>""" +
+ string.Concat(sheets.Select((_, i) => $"""<Override PartName="/xl/worksheets/sheet{i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>""")) +
+ "</Types>");
Add(zip, "_rels/.rels", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>
""");
- Add(zip, "xl/_rels/workbook.xml.rels", """
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>
- """);
- Add(zip, "xl/workbook.xml", $"""
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="{Escape(SheetName(sheet.Name))}" sheetId="1" r:id="rId1"/></sheets></workbook>
- """);
- Add(zip, "xl/styles.xml", """
- <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="11"/><name val="Calibri"/><family val="2"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>
- """);
- Add(zip, "xl/worksheets/sheet1.xml", SheetXml(sheet));
+ Add(zip, "xl/_rels/workbook.xml.rels",
+ """<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">""" +
+ string.Concat(sheets.Select((_, i) => $"""<Relationship Id="rId{i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{i + 1}.xml"/>""")) +
+ """<Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>""");
+ Add(zip, "xl/workbook.xml",
+ $"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="{Main}" xmlns:r="{RelationshipsNs}"><sheets>""" +
+ string.Concat(names.Select((name, i) => $"""<sheet name="{Escape(name)}" sheetId="{i + 1}" r:id="rId{i + 1}"/>""")) +
+ "</sheets></workbook>");
+ Add(zip, "xl/styles.xml", styles.Xml());
+ for (var i = 0; i < sheets.Count; i++)
+ Add(zip, $"xl/worksheets/sheet{i + 1}.xml", sheetXml[i]);
}
- private static string SheetXml(Worksheet sheet)
+ private static string SheetXml(Worksheet sheet, StyleTable styles, bool selected)
{
var sb = new StringBuilder("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>""");
- sb.Append("""<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">""");
- if (sheet.ColumnWidths.Count > 0)
- {
- sb.Append("<cols>");
- foreach (var (column, width) in sheet.ColumnWidths.OrderBy(kv => kv.Key))
- sb.Append(CultureInfo.InvariantCulture, $"<col min=\"{column + 1}\" max=\"{column + 1}\" width=\"{width:0.##}\" customWidth=\"1\"/>");
- sb.Append("</cols>");
- }
+ sb.Append(CultureInfo.InvariantCulture, $"""<worksheet xmlns="{Main}" xmlns:r="{RelationshipsNs}"><sheetViews><sheetView{(selected ? " tabSelected=\"1\"" : "")} workbookViewId="0">""");
+ if (sheet.FrozenRows > 0)
+ sb.Append(CultureInfo.InvariantCulture, $"""<pane ySplit="{sheet.FrozenRows}" topLeftCell="A{sheet.FrozenRows + 1}" activePane="bottomLeft" state="frozen"/>""");
+ sb.Append("</sheetView></sheetViews>");
+ sb.Append("""<sheetFormatPr defaultRowHeight="15" """);
+ if (Math.Abs(sheet.DefaultColumnWidth - Worksheet.StandardColumnWidth) > 0.005)
+ sb.Append(CultureInfo.InvariantCulture, $"""defaultColWidth="{sheet.DefaultColumnWidth:0.###}" """);
+ sb.Append("/>");
+ Columns(sb, sheet);
+
sb.Append("<sheetData>");
- foreach (var (row, cells) in sheet.Rows)
+ var rows = new SortedSet<int>(sheet.Rows.Keys);
+ rows.UnionWith(sheet.RowHeights.Keys);
+ rows.UnionWith(sheet.HiddenRows);
+ foreach (var row in rows)
{
- sb.Append(CultureInfo.InvariantCulture, $"<row r=\"{row + 1}\">");
- foreach (var (column, cell) in cells)
- {
- var reference = ColumnName(column) + (row + 1).ToString(CultureInfo.InvariantCulture);
- if (cell.IsNumber && double.TryParse(cell.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var number))
- sb.Append(CultureInfo.InvariantCulture, $"<c r=\"{reference}\"><v>{number.ToString("R", CultureInfo.InvariantCulture)}</v></c>");
- else
- sb.Append($"<c r=\"{reference}\" t=\"inlineStr\"><is><t xml:space=\"preserve\">{Escape(cell.Text)}</t></is></c>");
- }
+ sb.Append(CultureInfo.InvariantCulture, $"<row r=\"{row + 1}\"");
+ if (sheet.RowHeights.TryGetValue(row, out var height))
+ sb.Append(CultureInfo.InvariantCulture, $" ht=\"{height:0.##}\" customHeight=\"1\"");
+ if (sheet.HiddenRows.Contains(row))
+ sb.Append(" hidden=\"1\"");
+ sb.Append('>');
+ foreach (var (column, cell) in sheet.Rows.GetValueOrDefault(row) ?? [])
+ Cell(sb, ColumnName(column) + (row + 1).ToString(CultureInfo.InvariantCulture), cell, styles);
sb.Append("</row>");
}
- sb.Append("</sheetData></worksheet>");
+ sb.Append("</sheetData>");
+
+ if (sheet.Merges.Count > 0)
+ {
+ sb.Append(CultureInfo.InvariantCulture, $"<mergeCells count=\"{sheet.Merges.Count}\">");
+ foreach (var merge in sheet.Merges)
+ sb.Append(CultureInfo.InvariantCulture, $"<mergeCell ref=\"{ColumnName(merge.Left)}{merge.Top + 1}:{ColumnName(merge.Right)}{merge.Bottom + 1}\"/>");
+ sb.Append("</mergeCells>");
+ }
+ sb.Append("</worksheet>");
return sb.ToString();
}
+ /// <summary>&lt;cols&gt;: runs of neighbouring columns with the same width and visibility share one element.</summary>
+ private static void Columns(StringBuilder sb, Worksheet sheet)
+ {
+ var columns = sheet.ColumnWidths.Keys.Union(sheet.HiddenColumns).Order().ToList();
+ if (columns.Count == 0)
+ return;
+ sb.Append("<cols>");
+ for (var i = 0; i < columns.Count;)
+ {
+ var first = columns[i];
+ var width = sheet.ColumnWidth(first);
+ var hidden = sheet.HiddenColumns.Contains(first);
+ var last = first;
+ while (++i < columns.Count && columns[i] == last + 1 && sheet.ColumnWidth(columns[i]) == width && sheet.HiddenColumns.Contains(columns[i]) == hidden)
+ last = columns[i];
+ sb.Append(CultureInfo.InvariantCulture, $"<col min=\"{first + 1}\" max=\"{last + 1}\" width=\"{width:0.###}\" customWidth=\"1\"{(hidden ? " hidden=\"1\"" : "")}/>");
+ }
+ sb.Append("</cols>");
+ }
+
+ private static void Cell(StringBuilder sb, string reference, SheetCell cell, StyleTable styles)
+ {
+ var number = cell.Value ?? (cell.IsNumber && double.TryParse(cell.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed) ? parsed : null);
+ var style = styles.Index(cell.Style, number is null || cell.IsBoolean ? null : cell.NumberFormat);
+ var s = style == 0 ? "" : $" s=\"{style}\"";
+ if (cell.IsBoolean && number is { } flag)
+ sb.Append(CultureInfo.InvariantCulture, $"<c r=\"{reference}\"{s} t=\"b\"><v>{(flag != 0 ? 1 : 0)}</v></c>");
+ else if (number is { } value && double.IsFinite(value))
+ sb.Append(CultureInfo.InvariantCulture, $"<c r=\"{reference}\"{s}><v>{value.ToString("R", CultureInfo.InvariantCulture)}</v></c>");
+ else if (cell.Text.Length == 0)
+ sb.Append(CultureInfo.InvariantCulture, $"<c r=\"{reference}\"{s}/>");
+ else
+ sb.Append(CultureInfo.InvariantCulture, $"<c r=\"{reference}\"{s} t=\"inlineStr\"><is><t xml:space=\"preserve\">{Escape(cell.Text)}</t></is></c>");
+ }
+
/// <summary>0 → "A", 26 → "AA".</summary>
internal static string ColumnName(int column)
{
@@ -74,15 +143,28 @@ internal static class XlsxWriter
return name;
}
- /// <summary>Excel sheet names: at most 31 characters, none of : \ / ? * [ ].</summary>
- private static string SheetName(string name)
+ /// <summary>Excel sheet names: at most 31 characters, none of : \ / ? * [ ], unique ignoring case.</summary>
+ internal static List<string> UniqueNames(IEnumerable<string> names)
{
- var clean = new string([.. name.Where(ch => ch is not (':' or '\\' or '/' or '?' or '*' or '[' or ']'))]).Trim('\'').Trim();
- clean = clean.Length == 0 ? "Sheet1" : clean;
- return clean.Length > 31 ? clean[..31] : clean;
+ var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ var result = new List<string>();
+ foreach (var name in names)
+ {
+ var clean = new string([.. name.Where(ch => ch is not (':' or '\\' or '/' or '?' or '*' or '[' or ']'))]).Trim('\'').Trim();
+ clean = clean.Length == 0 ? "Sheet" + (result.Count + 1) : clean;
+ clean = clean.Length > 31 ? clean[..31] : clean;
+ var unique = clean;
+ for (var n = 2; !used.Add(unique); n++)
+ {
+ var suffix = $" ({n})";
+ unique = (clean.Length + suffix.Length > 31 ? clean[..(31 - suffix.Length)] : clean) + suffix;
+ }
+ result.Add(unique);
+ }
+ return result;
}
- private static string Escape(string text) =>
+ internal static string Escape(string text) =>
SecurityElement.Escape(new string([.. text.Where(ch => ch is '\t' or '\n' or '\r' || ch >= ' ')])) ?? "";
private static void Add(ZipArchive zip, string name, string content)
@@ -90,4 +172,85 @@ internal static class XlsxWriter
using var writer = new StreamWriter(zip.CreateEntry(name, CompressionLevel.Optimal).Open(), new UTF8Encoding(false));
writer.Write(content);
}
+
+ /// <summary>styles.xml: one cell format (xf) per distinct style and number format, sharing fonts, fills and borders.</summary>
+ private sealed class StyleTable
+ {
+ private readonly Dictionary<(CellStyle, string?), int> _xfs = new() { [(CellStyle.Default, null)] = 0 };
+ private readonly List<string> _xfXml = ["""<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>"""];
+ private readonly Dictionary<string, int> _formats = [];
+ private readonly List<string> _fonts = ["""<font><sz val="11"/><name val="Calibri"/><family val="2"/></font>"""];
+ private readonly List<string> _fills = ["""<fill><patternFill patternType="none"/></fill>""", """<fill><patternFill patternType="gray125"/></fill>"""];
+ private readonly List<string> _borders = ["<border><left/><right/><top/><bottom/><diagonal/></border>"];
+
+ /// <summary>The cellXfs index of a style with a number format (null = General).</summary>
+ public int Index(CellStyle style, string? format)
+ {
+ if (_xfs.TryGetValue((style, format), out var index))
+ return index;
+ var formatId = format is null ? 0 : BuiltInIds.TryGetValue(format, out var builtIn) ? builtIn : FormatId(format);
+ var fontId = Add(_fonts, Font(style));
+ var fillId = style.Fill is { } fill ? Add(_fills, $"""<fill><patternFill patternType="solid"><fgColor rgb="{Argb(fill)}"/><bgColor indexed="64"/></patternFill></fill>""") : 0;
+ var borderId = Add(_borders, $"<border>{Side("left", style.Left)}{Side("right", style.Right)}{Side("top", style.Top)}{Side("bottom", style.Bottom)}<diagonal/></border>");
+
+ var alignment = new StringBuilder();
+ if (style.Align != CellAlign.General)
+ alignment.Append(CultureInfo.InvariantCulture, $" horizontal=\"{style.Align.ToString().ToLowerInvariant()}\"");
+ if (style.VerticalAlign != CellVerticalAlign.Bottom)
+ alignment.Append(CultureInfo.InvariantCulture, $" vertical=\"{style.VerticalAlign.ToString().ToLowerInvariant()}\"");
+ if (style.Wrap)
+ alignment.Append(" wrapText=\"1\"");
+ var xf = $"""<xf numFmtId="{formatId}" fontId="{fontId}" fillId="{fillId}" borderId="{borderId}" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1">""" +
+ (alignment.Length > 0 ? $"<alignment{alignment}/>" : "") + "</xf>";
+ _xfXml.Add(xf);
+ return _xfs[(style, format)] = _xfXml.Count - 1;
+ }
+
+ public string Xml()
+ {
+ var sb = new StringBuilder($"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?><styleSheet xmlns="{Main}">""");
+ if (_formats.Count > 0)
+ {
+ sb.Append(CultureInfo.InvariantCulture, $"<numFmts count=\"{_formats.Count}\">");
+ foreach (var (code, id) in _formats)
+ sb.Append(CultureInfo.InvariantCulture, $"<numFmt numFmtId=\"{id}\" formatCode=\"{SecurityElement.Escape(code)}\"/>");
+ sb.Append("</numFmts>");
+ }
+ sb.Append(CultureInfo.InvariantCulture, $"<fonts count=\"{_fonts.Count}\">{string.Concat(_fonts)}</fonts>");
+ sb.Append(CultureInfo.InvariantCulture, $"<fills count=\"{_fills.Count}\">{string.Concat(_fills)}</fills>");
+ sb.Append(CultureInfo.InvariantCulture, $"<borders count=\"{_borders.Count}\">{string.Concat(_borders)}</borders>");
+ sb.Append("""<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>""");
+ sb.Append(CultureInfo.InvariantCulture, $"<cellXfs count=\"{_xfXml.Count}\">{string.Concat(_xfXml)}</cellXfs>");
+ sb.Append("""<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>""");
+ return sb.ToString();
+ }
+
+ /// <summary>Custom formats are numbered from 164, the first id Excel leaves to workbooks.</summary>
+ private int FormatId(string code)
+ {
+ if (!_formats.TryGetValue(code, out var id))
+ _formats[code] = id = 164 + _formats.Count;
+ return id;
+ }
+
+ private static string Font(CellStyle style) =>
+ "<font>" + (style.Bold ? "<b/>" : "") + (style.Italic ? "<i/>" : "") + (style.Strike ? "<strike/>" : "") + (style.Underline ? "<u/>" : "") +
+ string.Create(CultureInfo.InvariantCulture, $"<sz val=\"{style.FontSize ?? 11:0.##}\"/>") +
+ (style.Color is { } color ? $"<color rgb=\"{Argb(color)}\"/>" : "") + """<name val="Calibri"/><family val="2"/></font>""";
+
+ private static string Side(string name, CellBorder border) =>
+ border.IsVisible ? $"<{name} style=\"{border.Style}\"><color rgb=\"{Argb(border.Color ?? "#000000")}\"/></{name}>" : $"<{name}/>";
+
+ /// <summary>"#1F4E79" → "FF1F4E79".</summary>
+ private static string Argb(string color) => "FF" + color.TrimStart('#').ToUpperInvariant();
+
+ private static int Add(List<string> list, string xml)
+ {
+ var index = list.IndexOf(xml);
+ if (index >= 0)
+ return index;
+ list.Add(xml);
+ return list.Count - 1;
+ }
+ }
}
diff --git a/src/Filee.Engines/Office/SpreadsheetConverter.cs b/src/Filee.Engines/Office/SpreadsheetConverter.cs
index e28cf16c..4add85c1 100644
--- a/src/Filee.Engines/Office/SpreadsheetConverter.cs
+++ b/src/Filee.Engines/Office/SpreadsheetConverter.cs
@@ -1,5 +1,6 @@
-// XLSX → CSV and CSV → XLSX without Excel or LibreOffice. XLSX / CSV → PDF, HWPX and HTML go through the HWPX
-// writer (sheets become 한글 tables), see HwpxConverter and SheetDocument.
+// Spreadsheets between XLSX, XLS, ODS, CSV and TSV without Excel or LibreOffice (XLS and XLT are read, not written).
+// XLSX / XLS / ODS / CSV / TSV → PDF, HWPX and HTML go through the HWPX writer (sheets become 한글 tables), see
+// HwpxConverter and SheetDocument.
using Filee.Core.Conversion;
using Filee.Engines.Office.Sheets;
@@ -9,50 +10,68 @@ namespace Filee.Engines.Office;
/// <summary>Converts between spreadsheet formats in-process.</summary>
public sealed class SpreadsheetConverter : IConverter
{
+ private static readonly string[] Sources = ["xlsx", "xls", "ods", "csv", "tsv"];
+ private static readonly string[] Targets = ["xlsx", "ods", "csv", "tsv"];
+
public string Id => "spreadsheet";
public string DisplayName => "Spreadsheets (built-in)";
public int MaxParallelism => 0;
- public IReadOnlyList<ConversionEdge> Edges { get; } = [new("xlsx", "csv"), new("csv", "xlsx")];
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [.. Sources.SelectMany(from => Targets.Where(to => to != from).Select(to => new ConversionEdge(from, to)))];
- public EngineStatus GetStatus() => EngineStatus.Available("XLSX ↔ CSV");
+ public EngineStatus GetStatus() => EngineStatus.Available("XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV");
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
Task.Run<IReadOnlyList<string>>(() =>
{
progress?.Report(0.1);
- var book = step.From == "csv" ? CsvFormat.Read(step.InputPath) : XlsxReader.Read(step.InputPath);
+ var book = Read(step.InputPath, step.From);
cancellationToken.ThrowIfCancellationRequested();
progress?.Report(0.6);
var outputs = new List<string>();
- if (step.To == "xlsx")
- {
- if (step.Output.Allocate("xlsx") is { } path)
- {
- XlsxWriter.Write(book.Sheets[0], path);
- outputs.Add(path);
- }
- }
- else
+ switch (step.To)
{
- // CSV holds one sheet: a workbook with several sheets becomes one file per sheet.
- var sheets = book.Sheets.Where(s => s.UsedRange() is not null).ToList();
- if (sheets.Count == 0 && book.Sheets.Count > 0)
- sheets = [book.Sheets[0]];
- foreach (var sheet in sheets)
- {
- var path = step.Output.Allocate("csv", sheets.Count > 1 ? "_" + SafeName(sheet.Name) : null);
- if (path is null)
- continue;
- CsvFormat.Write(sheet, path);
- outputs.Add(path);
- }
+ case "xlsx" or "ods":
+ if (step.Output.Allocate(step.To) is { } path)
+ {
+ if (step.To == "xlsx")
+ XlsxWriter.Write(book, path);
+ else
+ OdsWriter.Write(book, path);
+ outputs.Add(path);
+ }
+ break;
+ default:
+ // CSV and TSV hold one sheet: a workbook with several sheets becomes one file per sheet.
+ var sheets = book.Sheets.Where(s => s.UsedRange() is not null).ToList();
+ if (sheets.Count == 0 && book.Sheets.Count > 0)
+ sheets = [book.Sheets[0]];
+ foreach (var sheet in sheets)
+ {
+ var file = step.Output.Allocate(step.To, sheets.Count > 1 ? "_" + SafeName(sheet.Name) : null);
+ if (file is null)
+ continue;
+ CsvFormat.Write(sheet, file, step.To == "tsv" ? CsvFormat.Tab : ',');
+ outputs.Add(file);
+ }
+ break;
}
progress?.Report(1);
return outputs;
}, cancellationToken);
+ /// <summary>Reads a spreadsheet of a format id this engine accepts.</summary>
+ internal static Workbook Read(string path, string format) => format switch
+ {
+ "xls" => XlsReader.Read(path),
+ "ods" => OdsReader.Read(path),
+ "csv" => CsvFormat.Read(path),
+ "tsv" => CsvFormat.ReadTsv(path),
+ _ => XlsxReader.Read(path),
+ };
+
private static string SafeName(string name)
{
var invalid = Path.GetInvalidFileNameChars();
diff --git a/tests/Filee.Engines.Tests/OfficeTests.cs b/tests/Filee.Engines.Tests/OfficeTests.cs
index 378e53db..5c094457 100644
--- a/tests/Filee.Engines.Tests/OfficeTests.cs
+++ b/tests/Filee.Engines.Tests/OfficeTests.cs
@@ -33,7 +33,7 @@ public class OfficeTests(EngineFixture fx) : IClassFixture<EngineFixture>
/// "매출": merged title, frozen header rows, number / date / percent formats, a formula, a boolean and an inline
/// string; "메모": a line break and a General number; "넓은 표": too wide for a portrait page; plus a hidden sheet.
/// </summary>
- private string SalesWorkbook(string folder)
+ internal static string SalesWorkbook(string folder)
{
var xlsx = new XlsxBuilder();
var date = new DateTime(2026, 10, 1).ToOADate();
@@ -279,9 +279,7 @@ public class OfficeTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Theory]
[InlineData("doc", "pdf")]
- [InlineData("xls", "xlsx")]
[InlineData("ppt", "pdf")]
- [InlineData("ods", "pdf")]
[InlineData("docx", "odt")]
public void Rare_formats_need_libreoffice(string from, string to)
{
diff --git a/tests/Filee.Engines.Tests/SpreadsheetBuilders.cs b/tests/Filee.Engines.Tests/SpreadsheetBuilders.cs
new file mode 100644
index 00000000..91fcc997
--- /dev/null
+++ b/tests/Filee.Engines.Tests/SpreadsheetBuilders.cs
@@ -0,0 +1,341 @@
+// Builds small .xls (Excel 97–2003, BIFF8 inside a compound file) and .ods files for tests, so the built-in XLS and
+// ODS readers can be tested without sample documents or LibreOffice (see OfficeBuilders.cs for .xlsx).
+
+using System.Buffers.Binary;
+using System.IO.Compression;
+using System.Text;
+
+namespace Filee.Engines.Tests;
+
+/// <summary>
+/// An Excel 97–2003 workbook: shared strings, a fixed set of cell formats and any number of sheets. Records follow
+/// [MS-XLS]; only what readers need is written (no INDEX / DBCELL records, no window settings).
+/// </summary>
+internal sealed class XlsBuilder
+{
+ // Cell formats (XF indexes):
+ public const int Plain = 0;
+ public const int Centered = 1; // centred horizontally
+ public const int Won = 2; // #,##0"원" (custom format 164)
+ public const int Date = 3; // built-in 14
+ public const int Percent = 4; // 0.0% (custom format 165)
+ public const int Time = 5; // built-in 20 (h:mm)
+ public const int RightTop = 6; // right aligned at the top
+
+ /// <summary>(format id, horizontal alignment, vertical alignment) of each XF.</summary>
+ private static readonly (int Format, int Horizontal, int Vertical)[] Xfs =
+ [(0, 0, 2), (0, 2, 2), (164, 0, 2), (14, 0, 2), (165, 0, 2), (20, 0, 2), (0, 3, 0)];
+
+ private static readonly (int Id, string Code)[] Formats = [(164, "#,##0\"원\""), (165, "0.0%")];
+
+ private readonly List<string> _strings = [];
+ private readonly List<XlsSheet> _sheets = [];
+
+ /// <summary>Adds a sheet; fill it through the returned builder.</summary>
+ public XlsSheet Sheet(string name, bool hidden = false)
+ {
+ var sheet = new XlsSheet(this, name, hidden);
+ _sheets.Add(sheet);
+ return sheet;
+ }
+
+ internal int StringIndex(string text)
+ {
+ var index = _strings.IndexOf(text);
+ if (index >= 0)
+ return index;
+ _strings.Add(text);
+ return _strings.Count - 1;
+ }
+
+ /// <param name="encrypted">Adds XOR obfuscation with a password nobody knows, as a protected file has.</param>
+ public string Save(string path, bool encrypted = false)
+ {
+ var stream = new MemoryStream();
+ Record(stream, 0x0809, Bof(0x0005));
+ if (encrypted)
+ Record(stream, 0x002F, [0x00, 0x00, 0x34, 0x12, 0x01, 0x00]); // FILEPASS: XOR, key 0x1234, verifier 0x0001
+ Record(stream, 0x0042, U16(1200)); // CODEPAGE: UTF-16
+ for (var i = 0; i < 5; i++)
+ Record(stream, 0x0031, Font(bold: i == 1));
+ foreach (var (id, code) in Formats)
+ Record(stream, 0x041E, [.. U16(id), .. UnicodeString(code, byteLength: false)]);
+ foreach (var (format, horizontal, vertical) in Xfs)
+ Record(stream, 0x00E0, Xf(format, horizontal, vertical));
+
+ var sheetOffsets = new List<long>();
+ foreach (var sheet in _sheets)
+ {
+ sheetOffsets.Add(stream.Position + 4);
+ Record(stream, 0x0085, [0, 0, 0, 0, (byte)(sheet.Hidden ? 1 : 0), 0, .. UnicodeString(sheet.Name, byteLength: true)]);
+ }
+ var sst = new List<byte>();
+ sst.AddRange(U32(_strings.Count));
+ sst.AddRange(U32(_strings.Count));
+ foreach (var text in _strings)
+ sst.AddRange(UnicodeString(text, byteLength: false));
+ Record(stream, 0x00FC, [.. sst]);
+ Record(stream, 0x000A, []);
+
+ for (var i = 0; i < _sheets.Count; i++)
+ {
+ var offset = stream.Position;
+ var position = stream.Position;
+ stream.Position = sheetOffsets[i];
+ stream.Write(U32((int)offset));
+ stream.Position = position;
+ _sheets[i].Write(stream);
+ }
+
+ CompoundFile.Write(path, "Workbook", stream.ToArray());
+ return path;
+ }
+
+ internal static byte[] Bof(int type) => [.. U16(0x0600), .. U16(type), .. U16(0x0DBB), .. U16(0x07CC), 0, 0, 0, 0, 6, 0, 0, 0];
+
+ private static byte[] Font(bool bold) =>
+ [.. U16(220), .. U16(0), .. U16(0x7FFF), .. U16(bold ? 700 : 400), .. U16(0), 0, 0, 0, 0, .. UnicodeString("Arial", byteLength: true)];
+
+ private static byte[] Xf(int format, int horizontal, int vertical)
+ {
+ var xf = new byte[20];
+ BinaryPrimitives.WriteUInt16LittleEndian(xf, 0);
+ BinaryPrimitives.WriteUInt16LittleEndian(xf.AsSpan(2), (ushort)format);
+ BinaryPrimitives.WriteUInt16LittleEndian(xf.AsSpan(4), 0x0001); // locked cell XF, parent style 0
+ xf[6] = (byte)(horizontal | vertical << 4);
+ xf[9] = 0xFC; // all attribute groups set by this XF
+ return xf;
+ }
+
+ /// <summary>A BIFF8 string with a 1-byte (ShortXLUnicodeString) or 2-byte length, stored as UTF-16.</summary>
+ internal static byte[] UnicodeString(string text, bool byteLength) =>
+ [.. byteLength ? [(byte)text.Length] : U16(text.Length), 0x01, .. Encoding.Unicode.GetBytes(text)];
+
+ internal static void Record(Stream stream, int id, byte[] data)
+ {
+ stream.Write(U16(id));
+ stream.Write(U16(data.Length));
+ stream.Write(data);
+ }
+
+ internal static byte[] U16(int value) => BitConverter.GetBytes((ushort)value);
+ internal static byte[] U32(int value) => BitConverter.GetBytes(value);
+}
+
+/// <summary>One sheet of an <see cref="XlsBuilder"/> workbook; rows and columns are 0-based.</summary>
+internal sealed class XlsSheet(XlsBuilder book, string name, bool hidden)
+{
+ private readonly SortedDictionary<(int Row, int Column), byte[]> _cells = [];
+ private readonly List<(int Top, int Left, int Bottom, int Right)> _merges = [];
+ private readonly List<(int Column, double Width, bool Hidden)> _columns = [];
+ private readonly SortedDictionary<int, (double Points, bool Hidden)> _rows = [];
+
+ public string Name => name;
+ public bool Hidden => hidden;
+
+ public XlsSheet Text(int row, int column, string text, int xf = XlsBuilder.Plain) =>
+ Cell(0x00FD, row, column, xf, XlsBuilder.U32(book.StringIndex(text)));
+
+ public XlsSheet Number(int row, int column, double value, int xf = XlsBuilder.Plain) =>
+ Cell(0x0203, row, column, xf, BitConverter.GetBytes(value));
+
+ public XlsSheet Bool(int row, int column, bool value) => Cell(0x0205, row, column, XlsBuilder.Plain, [(byte)(value ? 1 : 0), 0]);
+
+ /// <summary>An error cell: 0x07 = #DIV/0!, 0x2A = #N/A.</summary>
+ public XlsSheet Error(int row, int column, byte code) => Cell(0x0205, row, column, XlsBuilder.Plain, [code, 1]);
+
+ public XlsSheet Merge(int top, int left, int bottom, int right)
+ {
+ _merges.Add((top, left, bottom, right));
+ return this;
+ }
+
+ /// <summary>A column width in characters (as Excel shows it), or a hidden column.</summary>
+ public XlsSheet Width(int column, double characters, bool hide = false)
+ {
+ _columns.Add((column, characters, hide));
+ return this;
+ }
+
+ public XlsSheet Height(int row, double points, bool hide = false)
+ {
+ _rows[row] = (points, hide);
+ return this;
+ }
+
+ private XlsSheet Cell(int id, int row, int column, int xf, byte[] value)
+ {
+ _cells[(row, column)] = [.. XlsBuilder.U16(id), .. XlsBuilder.U16(row), .. XlsBuilder.U16(column), .. XlsBuilder.U16(xf), .. value];
+ return this;
+ }
+
+ internal void Write(Stream stream)
+ {
+ XlsBuilder.Record(stream, 0x0809, XlsBuilder.Bof(0x0010));
+ XlsBuilder.Record(stream, 0x0225, [.. XlsBuilder.U16(0), .. XlsBuilder.U16(300)]); // DEFAULTROWHEIGHT: 15 pt
+ foreach (var (column, width, hide) in _columns)
+ {
+ // COLINFO: width in 1/256 characters; fUserSet so readers take the width.
+ XlsBuilder.Record(stream, 0x007D,
+ [.. XlsBuilder.U16(column), .. XlsBuilder.U16(column), .. XlsBuilder.U16((int)(width * 256)), .. XlsBuilder.U16(15), .. XlsBuilder.U16(hide ? 0x0003 : 0x0002), .. XlsBuilder.U16(0)]);
+ }
+ var lastRow = _cells.Keys.Select(k => k.Row).Concat(_rows.Keys).DefaultIfEmpty(-1).Max();
+ var lastColumn = _cells.Keys.Select(k => k.Column).DefaultIfEmpty(-1).Max();
+ XlsBuilder.Record(stream, 0x0200, [.. XlsBuilder.U32(0), .. XlsBuilder.U32(lastRow + 1), .. XlsBuilder.U16(0), .. XlsBuilder.U16(lastColumn + 1), .. XlsBuilder.U16(0)]);
+
+ foreach (var (row, (points, hide)) in _rows)
+ {
+ // ROW: fDyZero (0x20) hides the row, fUnsynced (0x40) marks a custom height; the high byte must be 1.
+ var flags = 0x0100 | 0x0040 | (hide ? 0x0020 : 0);
+ XlsBuilder.Record(stream, 0x0208,
+ [.. XlsBuilder.U16(row), .. XlsBuilder.U16(0), .. XlsBuilder.U16(lastColumn + 1), .. XlsBuilder.U16((int)(points * 20)), .. XlsBuilder.U16(0), .. XlsBuilder.U16(0), .. XlsBuilder.U16(flags), .. XlsBuilder.U16(15)]);
+ }
+ foreach (var cell in _cells.Values)
+ XlsBuilder.Record(stream, BitConverter.ToUInt16(cell, 0), cell[2..]);
+ if (_merges.Count > 0)
+ {
+ var data = new List<byte>(XlsBuilder.U16(_merges.Count));
+ foreach (var (top, left, bottom, right) in _merges)
+ data.AddRange([.. XlsBuilder.U16(top), .. XlsBuilder.U16(bottom), .. XlsBuilder.U16(left), .. XlsBuilder.U16(right)]);
+ XlsBuilder.Record(stream, 0x00E5, [.. data]);
+ }
+ XlsBuilder.Record(stream, 0x000A, []);
+ }
+}
+
+/// <summary>
+/// Writes a compound file (the OLE2 container of .xls, .doc and .ppt) holding one stream. Like Office, streams under
+/// 4096 bytes go into the mini stream (64-byte sectors kept in the root entry).
+/// </summary>
+internal static class CompoundFile
+{
+ private const int SectorSize = 512;
+ private const int MiniSectorSize = 64;
+ private const int MiniStreamCutoff = 4096;
+ private const uint EndOfChain = 0xFFFFFFFE;
+ private const uint FreeSector = 0xFFFFFFFF;
+ private const uint FatSectorMark = 0xFFFFFFFD;
+ private const uint NoStream = 0xFFFFFFFF;
+
+ public static void Write(string path, string streamName, byte[] data)
+ {
+ var mini = data.Length < MiniStreamCutoff;
+ var miniSectors = (data.Length + MiniSectorSize - 1) / MiniSectorSize;
+ // Mini streams: sectors 0.. hold the mini stream, then one sector of mini FAT.
+ var content = mini ? [.. data, .. new byte[miniSectors * MiniSectorSize - data.Length]] : data;
+ var dataSectors = (content.Length + SectorSize - 1) / SectorSize;
+ var miniFatSector = mini ? dataSectors : -1;
+ var directorySector = dataSectors + (mini ? 1 : 0);
+ var fatSectors = 1;
+ while (fatSectors * (SectorSize / 4) < directorySector + 1 + fatSectors)
+ fatSectors++;
+
+ var fat = Enumerable.Repeat(FreeSector, fatSectors * (SectorSize / 4)).ToArray();
+ for (var i = 0; i < dataSectors; i++)
+ fat[i] = i + 1 < dataSectors ? (uint)(i + 1) : EndOfChain;
+ if (mini)
+ fat[miniFatSector] = EndOfChain;
+ fat[directorySector] = EndOfChain;
+ for (var i = 0; i < fatSectors; i++)
+ fat[directorySector + 1 + i] = FatSectorMark;
+
+ using var file = File.Create(path);
+ var header = new byte[SectorSize];
+ new byte[] { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 }.CopyTo(header, 0);
+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(24), 0x003E); // minor version
+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(26), 0x0003); // major version 3: 512-byte sectors
+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(28), 0xFFFE); // little endian
+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(30), 9); // sector size 2^9
+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(32), 6); // mini sector size 2^6
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(44), (uint)fatSectors);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(48), (uint)directorySector);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(56), MiniStreamCutoff);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(60), mini ? (uint)miniFatSector : EndOfChain);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(64), mini ? 1u : 0u);
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(68), EndOfChain);
+ for (var i = 0; i < 109; i++)
+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(76 + i * 4), i < fatSectors ? (uint)(directorySector + 1 + i) : FreeSector);
+ file.Write(header);
+
+ file.Write(content);
+ file.Write(new byte[dataSectors * SectorSize - content.Length]);
+ if (mini)
+ {
+ var miniFat = Enumerable.Repeat(FreeSector, SectorSize / 4).ToArray();
+ for (var i = 0; i < miniSectors; i++)
+ miniFat[i] = i + 1 < miniSectors ? (uint)(i + 1) : EndOfChain;
+ foreach (var entry in miniFat)
+ file.Write(BitConverter.GetBytes(entry));
+ }
+
+ var directory = new byte[SectorSize];
+ Entry(directory.AsSpan(0, 128), "Root Entry", type: 5, child: 1, start: mini ? 0 : EndOfChain, size: mini ? content.Length : 0);
+ Entry(directory.AsSpan(128, 128), streamName, type: 2, child: NoStream, start: 0, size: data.Length);
+ Entry(directory.AsSpan(256, 128), "", type: 0, child: NoStream, start: 0, size: 0);
+ Entry(directory.AsSpan(384, 128), "", type: 0, child: NoStream, start: 0, size: 0);
+ file.Write(directory);
+
+ foreach (var entry in fat)
+ file.Write(BitConverter.GetBytes(entry));
+ }
+
+ private static void Entry(Span<byte> entry, string name, byte type, uint child, uint start, int size)
+ {
+ if (name.Length > 0)
+ {
+ Encoding.Unicode.GetBytes(name).CopyTo(entry);
+ BinaryPrimitives.WriteUInt16LittleEndian(entry[64..], (ushort)((name.Length + 1) * 2));
+ }
+ entry[66] = type;
+ entry[67] = 1; // black node of the red-black tree
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[68..], NoStream); // left sibling
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[72..], NoStream); // right sibling
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[76..], child);
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[116..], start);
+ BinaryPrimitives.WriteUInt32LittleEndian(entry[120..], (uint)size);
+ }
+}
+
+/// <summary>Writes an .ods package from hand-written content.xml (and optionally styles.xml / settings.xml).</summary>
+internal static class OdsBuilder
+{
+ public const string Namespaces =
+ "xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" " +
+ "xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\" " +
+ "xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" " +
+ "xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" " +
+ "xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\" " +
+ "xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\" " +
+ "xmlns:config=\"urn:oasis:names:tc:opendocument:xmlns:config:1.0\" " +
+ "xmlns:calcext=\"urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0\"";
+
+ /// <param name="automaticStyles">Children of office:automatic-styles in content.xml.</param>
+ /// <param name="tables">table:table elements.</param>
+ /// <param name="styles">Children of office:styles in styles.xml.</param>
+ /// <param name="settings">settings.xml content (without the declaration), or null.</param>
+ /// <param name="encrypted">Declares content.xml as encrypted in the manifest, as password-protected files do.</param>
+ public static string Save(string path, string automaticStyles, string tables, string styles = "", string? settings = null, bool encrypted = false)
+ {
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ Add(zip, "mimetype", "application/vnd.oasis.opendocument.spreadsheet", CompressionLevel.NoCompression);
+ Add(zip, "content.xml", OpcWriter.Declaration +
+ $"<office:document-content {Namespaces} office:version=\"1.3\"><office:automatic-styles>{automaticStyles}</office:automatic-styles>" +
+ $"<office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body></office:document-content>");
+ Add(zip, "styles.xml", OpcWriter.Declaration + $"<office:document-styles {Namespaces} office:version=\"1.3\"><office:styles>{styles}</office:styles></office:document-styles>");
+ if (settings is not null)
+ Add(zip, "settings.xml", OpcWriter.Declaration + settings);
+ Add(zip, "META-INF/manifest.xml", OpcWriter.Declaration +
+ "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.3\">" +
+ "<manifest:file-entry manifest:full-path=\"/\" manifest:media-type=\"application/vnd.oasis.opendocument.spreadsheet\"/>" +
+ "<manifest:file-entry manifest:full-path=\"content.xml\" manifest:media-type=\"text/xml\">" +
+ (encrypted ? "<manifest:encryption-data manifest:checksum-type=\"SHA1/1K\" manifest:checksum=\"AAAA\"><manifest:algorithm manifest:algorithm-name=\"Blowfish CFB\" manifest:initialisation-vector=\"AAAA\"/></manifest:encryption-data>" : "") +
+ "</manifest:file-entry></manifest:manifest>");
+ return path;
+ }
+
+ private static void Add(ZipArchive zip, string name, string content, CompressionLevel level = CompressionLevel.Optimal)
+ {
+ using var writer = new StreamWriter(zip.CreateEntry(name, level).Open(), new UTF8Encoding(false));
+ writer.Write(content);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/SpreadsheetFormatTests.cs b/tests/Filee.Engines.Tests/SpreadsheetFormatTests.cs
new file mode 100644
index 00000000..738fce0d
--- /dev/null
+++ b/tests/Filee.Engines.Tests/SpreadsheetFormatTests.cs
@@ -0,0 +1,629 @@
+// XLS, ODS and TSV without Excel or LibreOffice: XLS and ODS are read in-process with what the cells show, values
+// and number formats, XLSX / XLS / ODS / CSV / TSV convert to each other keeping real numbers, and XLS / ODS / TSV
+// become HWPX and PDF. Inputs come from XlsBuilder, OdsBuilder and XlsxBuilder; LibreOffice, when installed,
+// cross-checks the ODS we write and the ODS / XLS it writes.
+
+using System.IO.Compression;
+using System.Text;
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Office;
+using Filee.Engines.Office.Sheets;
+
+namespace Filee.Engines.Tests;
+
+public class SpreadsheetFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly XNamespace S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
+ private static readonly XNamespace Office = "urn:oasis:names:tc:opendocument:xmlns:office:1.0";
+ private static readonly XNamespace Table = "urn:oasis:names:tc:opendocument:xmlns:table:1.0";
+ private static readonly XNamespace Text = "urn:oasis:names:tc:opendocument:xmlns:text:1.0";
+ private static readonly XNamespace Number = "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0";
+ private static readonly XNamespace Style = "urn:oasis:names:tc:opendocument:xmlns:style:1.0";
+
+ /// <summary>1 October 2026 as an Excel serial date.</summary>
+ private const double October1 = 46296;
+
+ private static readonly string[] OptionalEngines = ["pandoc", "libreoffice"];
+
+ private RoutePlanner BuiltInPlanner(params string[] assumeInstalled) =>
+ new ConverterCatalog(fx.Converters.Where(c => !OptionalEngines.Contains(c.Id))) { Priority = fx.Catalog.Priority }
+ .CreatePlanner(assumeInstalled);
+
+ private async Task<IReadOnlyList<string>> ConvertAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return [.. job.Outputs];
+ }
+
+ /// <summary>
+ /// "매출": centred title merged over four columns, number / date / percent / time formats, a boolean, an error,
+ /// custom widths, a hidden row and column, a taller row; "비밀" is hidden; "메모" holds a line break.
+ /// </summary>
+ /// <param name="filler">Rows of numbers added to "메모": files under 4 KB keep the workbook in the compound
+ /// file's mini stream, bigger ones in regular sectors.</param>
+ private static string SalesXls(string folder, int filler = 0)
+ {
+ var xls = new XlsBuilder();
+ xls.Sheet("매출")
+ .Text(0, 0, "지점별 매출", XlsBuilder.Centered).Merge(0, 0, 0, 3)
+ .Text(1, 0, "지점").Text(1, 1, "매출").Text(1, 2, "일자").Text(1, 3, "성장률")
+ .Text(2, 0, "서울 강남").Number(2, 1, 1350000, XlsBuilder.Won).Number(2, 2, October1, XlsBuilder.Date).Number(2, 3, 0.128, XlsBuilder.Percent)
+ .Text(2, 4, "숨긴 열")
+ .Text(3, 0, "부산 서면").Number(3, 1, 870000, XlsBuilder.Won).Number(3, 2, October1 + 1, XlsBuilder.Date).Number(3, 3, 0.09, XlsBuilder.Percent)
+ .Text(4, 0, "합계").Number(4, 1, 2220000, XlsBuilder.Won).Bool(4, 2, true).Error(4, 3, 0x07)
+ .Text(5, 0, "숨긴 행").Height(5, 15, hide: true)
+ .Number(6, 0, 0.5, XlsBuilder.Time).Number(6, 1, 3.5).Text(6, 2, "오른쪽 위", XlsBuilder.RightTop).Height(6, 30)
+ .Width(0, 14).Width(1, 12).Width(2, 12).Width(3, 12).Width(4, 20, hide: true);
+ xls.Sheet("비밀", hidden: true).Text(0, 0, "보이면 안 됨");
+ var memo = xls.Sheet("메모").Text(0, 0, "첫 줄\n둘째 줄").Number(1, 0, 42);
+ for (var i = 0; i < filler; i++)
+ memo.Number(2 + i, 0, i * 1.5);
+ return xls.Save(Path.Combine(folder, "매출보고.xls"));
+ }
+
+ // ───────────────────────── XLS ─────────────────────────
+
+ [Fact]
+ public void Xls_values_formats_and_layout_are_read_like_excel_shows_them()
+ {
+ var book = XlsReader.Read(SalesXls(fx.NewFolder()));
+
+ Assert.Equal(["매출", "메모"], book.Sheets.Select(s => s.Name)); // the hidden sheet is left out
+ var sales = book.Sheets[0];
+ var won = sales.Get(2, 1)!;
+ Assert.Equal(("1,350,000원", true, 1350000.0, "#,##0\"원\""), (won.Text, won.IsNumber, won.Value, won.NumberFormat));
+ var date = sales.Get(2, 2)!;
+ Assert.Equal(("2026-10-01", October1, "yyyy-mm-dd"), (date.Text, date.Value, date.NumberFormat));
+ Assert.Equal(("12.8%", "0.0%"), (sales.Get(2, 3)!.Text, sales.Get(2, 3)!.NumberFormat));
+ Assert.Equal("2,220,000원", sales.Get(4, 1)!.Text);
+ Assert.Equal(("TRUE", true, 1.0), (sales.Get(4, 2)!.Text, sales.Get(4, 2)!.IsBoolean, sales.Get(4, 2)!.Value));
+ Assert.Equal(("#DIV/0!", false), (sales.Get(4, 3)!.Text, sales.Get(4, 3)!.IsNumber));
+ var time = sales.Get(6, 0)!;
+ Assert.Equal(("12:00", 0.5, "h:mm"), (time.Text, time.Value, time.NumberFormat));
+ Assert.Equal(("3.5", null), (sales.Get(6, 1)!.Text, sales.Get(6, 1)!.NumberFormat)); // General
+
+ Assert.Equal(CellAlign.Center, sales.Get(0, 0)!.Style.Align);
+ Assert.Equal((CellAlign.Right, CellVerticalAlign.Top), (sales.Get(6, 2)!.Style.Align, sales.Get(6, 2)!.Style.VerticalAlign));
+ Assert.Equal(new CellRange(0, 0, 0, 3), Assert.Single(sales.Merges));
+ Assert.Equal([14.0, 12.0, 12.0, 12.0], Enumerable.Range(0, 4).Select(sales.ColumnWidth));
+ Assert.Equal([4], sales.HiddenColumns);
+ Assert.Equal([5], sales.HiddenRows);
+ Assert.Equal(30, Assert.Single(sales.RowHeights).Value); // only the row that differs from the usual height
+
+ var memo = book.Sheets[1];
+ Assert.Equal("첫 줄\n둘째 줄", memo.Get(0, 0)!.Text);
+ Assert.Equal("42", memo.Get(1, 0)!.Text);
+ }
+
+ [Fact]
+ public async Task Password_protected_xls_fails_with_a_clear_message()
+ {
+ var xls = new XlsBuilder();
+ xls.Sheet("Sheet1").Text(0, 0, "secret");
+ var path = xls.Save(Path.Combine(fx.NewFolder(), "잠금.xls"), encrypted: true);
+
+ Assert.Contains("password", Assert.Throws<InvalidDataException>(() => XlsReader.Read(path)).Message);
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "xlsx" });
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Contains("password", Assert.Single(job.Files).ErrorDetail);
+ }
+
+ [Fact]
+ public void Xlsx_saved_with_an_xls_name_is_read_as_xlsx()
+ {
+ var dir = fx.NewFolder();
+ var xls = Path.Combine(dir, "웹에서 받은 파일.xls");
+ File.Copy(OfficeTests.SalesWorkbook(dir), xls);
+
+ var sales = XlsReader.Read(xls).Sheets[0];
+
+ Assert.Equal("1,350,000원", sales.Get(2, 1)!.Text);
+ Assert.Equal("#1F4E79", sales.Get(1, 0)!.Style.Fill); // what the XLSX reader keeps and ExcelDataReader doesn't
+ }
+
+ [Fact]
+ public async Task Xls_to_xlsx_keeps_numbers_dates_and_their_formats()
+ {
+ var dir = fx.NewFolder();
+ var xls = SalesXls(dir, filler: 400);
+ Assert.True(new FileInfo(xls).Length > 8192);
+ var source = XlsReader.Read(xls);
+
+ var xlsx = Assert.Single(await ConvertAsync(xls, "xlsx"));
+
+ using (var zip = ZipFile.OpenRead(xlsx))
+ {
+ XElement Part(string name)
+ {
+ using var stream = zip.GetEntry(name)!.Open();
+ return XElement.Load(stream);
+ }
+ Assert.Equal(["매출", "메모"], Part("xl/workbook.xml").Descendants(S + "sheet").Select(s => (string)s.Attribute("name")!));
+ var cells = Part("xl/worksheets/sheet1.xml").Descendants(S + "c").ToDictionary(c => (string)c.Attribute("r")!);
+ var styles = Part("xl/styles.xml");
+ var xfs = styles.Element(S + "cellXfs")!.Elements(S + "xf").ToList();
+ string FormatCode(string reference)
+ {
+ var id = (int)xfs[(int)cells[reference].Attribute("s")!].Attribute("numFmtId")!;
+ return (string)styles.Descendants(S + "numFmt").Single(f => (int)f.Attribute("numFmtId")! == id).Attribute("formatCode")!;
+ }
+ // Real numbers with their formats, not text: Excel can calculate with them.
+ Assert.Null(cells["B3"].Attribute("t"));
+ Assert.Equal("1350000", (string)cells["B3"].Element(S + "v")!);
+ Assert.Equal("#,##0\"원\"", FormatCode("B3"));
+ Assert.Equal(("46296", "yyyy-mm-dd"), ((string)cells["C3"].Element(S + "v")!, FormatCode("C3")));
+ Assert.Equal("b", (string?)cells["C5"].Attribute("t"));
+ }
+
+ var result = XlsxReader.Read(xlsx);
+ AssertSameCells(source, result);
+ Assert.Equal(source.Sheets[0].Merges, result.Sheets[0].Merges);
+ Assert.Equal(source.Sheets[0].HiddenRows, result.Sheets[0].HiddenRows);
+ Assert.Equal(14, result.Sheets[0].ColumnWidth(0));
+ }
+
+ // ───────────────────────── ODS ─────────────────────────
+
+ private const string OdsStyles =
+ """
+ <style:default-style style:family="table-cell"><style:text-properties fo:font-size="10pt"/></style:default-style>
+ <style:style style:name="Default" style:family="table-cell"/>
+ <style:style style:name="Heading" style:family="table-cell" style:parent-style-name="Default"><style:text-properties fo:font-weight="bold" fo:font-size="14pt"/></style:style>
+ <number:number-style style:name="N4"><number:number number:decimal-places="2" number:min-decimal-places="2" number:min-integer-digits="1" number:grouping="true"/></number:number-style>
+ """;
+
+ private const string OdsAutomaticStyles =
+ """
+ <style:style style:name="co1" style:family="table-column"><style:table-column-properties style:column-width="2.54cm"/></style:style>
+ <style:style style:name="co2" style:family="table-column"><style:table-column-properties style:column-width="0.8in"/></style:style>
+ <style:style style:name="ro1" style:family="table-row"><style:table-row-properties style:row-height="0.178in" style:use-optimal-row-height="true"/></style:style>
+ <style:style style:name="ro2" style:family="table-row"><style:table-row-properties style:row-height="30pt" style:use-optimal-row-height="false"/></style:style>
+ <style:style style:name="ta1" style:family="table"><style:table-properties table:display="true"/></style:style>
+ <style:style style:name="ta2" style:family="table"><style:table-properties table:display="false"/></style:style>
+ <number:percentage-style style:name="N10"><number:number number:decimal-places="1" number:min-decimal-places="1" number:min-integer-digits="1"/><number:text>%</number:text></number:percentage-style>
+ <number:currency-style style:name="N11P0" style:volatile="true"><number:currency-symbol>₩</number:currency-symbol><number:number number:decimal-places="0" number:min-integer-digits="1" number:grouping="true"/></number:currency-style>
+ <number:currency-style style:name="N11"><style:text-properties fo:color="#ff0000"/><number:text>-</number:text><number:currency-symbol>₩</number:currency-symbol><number:number number:decimal-places="0" number:min-integer-digits="1" number:grouping="true"/><style:map style:condition="value()&gt;=0" style:apply-style-name="N11P0"/></number:currency-style>
+ <number:date-style style:name="N12"><number:year number:style="long"/><number:text>년 </number:text><number:month/><number:text>월 </number:text><number:day/><number:text>일</number:text></number:date-style>
+ <number:time-style style:name="N13"><number:hours number:style="long"/><number:text>:</number:text><number:minutes number:style="long"/></number:time-style>
+ <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Heading"><style:table-cell-properties fo:background-color="#1f4e79" fo:border="0.75pt solid #000000" style:text-align-source="fix" style:vertical-align="middle"/><style:paragraph-properties fo:text-align="center"/><style:text-properties fo:color="#ffffff"/></style:style>
+ <style:style style:name="ce2" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N4"/>
+ <style:style style:name="ce3" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N10"/>
+ <style:style style:name="ce4" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N11"/>
+ <style:style style:name="ce5" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N12"/>
+ <style:style style:name="ce6" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N13"/>
+ <style:style style:name="ce7" style:family="table-cell" style:parent-style-name="Default"><style:table-cell-properties fo:border-bottom="2.5pt double #c00000" fo:wrap-option="wrap"/><style:text-properties fo:font-style="italic" style:text-underline-style="solid" style:text-line-through-style="solid"/></style:style>
+ <style:style style:name="ce8" style:family="table-cell" style:parent-style-name="Default"><style:table-cell-properties fo:background-color="#ffff00"/></style:style>
+ """;
+
+ /// <summary>
+ /// Laid out like LibreOffice saves sheets: repeated columns and rows up to the end of the sheet, a merged
+ /// header row, every value type, text with spaces, tabs, line breaks and a comment, a hidden row, column and
+ /// sheet, and a sheet whose formatting reaches the last row.
+ /// </summary>
+ private const string OdsTables =
+ """
+ <table:table table:name="매출" table:style-name="ta1">
+ <table:table-column table:style-name="co1" table:default-cell-style-name="Default"/>
+ <table:table-column table:style-name="co2" table:number-columns-repeated="2" table:default-cell-style-name="Default"/>
+ <table:table-column table:style-name="co2" table:visibility="collapse" table:default-cell-style-name="Default"/>
+ <table:table-column table:style-name="co1" table:number-columns-repeated="16380" table:default-cell-style-name="Default"/>
+ <table:table-header-rows>
+ <table:table-row table:style-name="ro2">
+ <table:table-cell table:style-name="ce1" office:value-type="string" table:number-columns-spanned="3" table:number-rows-spanned="1"><text:p>지점별 매출</text:p></table:table-cell>
+ <table:covered-table-cell table:number-columns-repeated="2"/>
+ <table:table-cell table:number-columns-repeated="16381"/>
+ </table:table-row>
+ </table:table-header-rows>
+ <table:table-row table:style-name="ro1">
+ <table:table-cell table:style-name="ce2" office:value-type="float" office:value="1234.5"><text:p>1,234.50</text:p></table:table-cell>
+ <table:table-cell table:style-name="ce3" office:value-type="percentage" office:value="0.128"><text:p>12.8%</text:p></table:table-cell>
+ <table:table-cell table:style-name="ce4" office:value-type="currency" office:currency="KRW" office:value="-5000"><text:p>-₩5,000</text:p></table:table-cell>
+ <table:table-cell table:number-columns-repeated="16381"/>
+ </table:table-row>
+ <table:table-row table:style-name="ro1">
+ <table:table-cell table:style-name="ce5" office:value-type="date" office:date-value="2026-10-01"><text:p>2026년 10월 1일</text:p></table:table-cell>
+ <table:table-cell table:style-name="ce6" office:value-type="time" office:time-value="PT13H30M00S"><text:p>13:30</text:p></table:table-cell>
+ <table:table-cell office:value-type="boolean" office:boolean-value="true"><text:p>TRUE</text:p></table:table-cell>
+ <table:table-cell office:value-type="string" calcext:value-type="error"><text:p>#DIV/0!</text:p></table:table-cell>
+ <table:table-cell table:number-columns-repeated="16380"/>
+ </table:table-row>
+ <table:table-row table:style-name="ro1" table:number-rows-repeated="2">
+ <table:table-cell office:value-type="float" office:value="7" table:number-columns-repeated="3"><text:p>7</text:p></table:table-cell>
+ <table:table-cell table:number-columns-repeated="16381"/>
+ </table:table-row>
+ <table:table-row table:style-name="ro1" table:visibility="collapse">
+ <table:table-cell office:value-type="string"><text:p>숨긴 행</text:p></table:table-cell>
+ <table:table-cell table:number-columns-repeated="16383"/>
+ </table:table-row>
+ <table:table-row table:style-name="ro1">
+ <table:table-cell table:style-name="ce7" office:value-type="string"><office:annotation><text:p>메모는 셀 내용이 아님</text:p></office:annotation><text:p><text:s/>앞 공백<text:s text:c="2"/>세 칸<text:tab/>탭<text:line-break/>줄</text:p><text:p><text:span>둘째</text:span> <text:span>문단</text:span></text:p></table:table-cell>
+ <table:table-cell table:number-columns-repeated="16383"/>
+ </table:table-row>
+ <table:table-row table:style-name="ro1" table:number-rows-repeated="1048569">
+ <table:table-cell table:number-columns-repeated="16384"/>
+ </table:table-row>
+ </table:table>
+ <table:table table:name="비밀" table:style-name="ta2">
+ <table:table-column/>
+ <table:table-row><table:table-cell office:value-type="string"><text:p>보이면 안 됨</text:p></table:table-cell></table:table-row>
+ </table:table>
+ <table:table table:name="색칠" table:style-name="ta1">
+ <table:table-column table:default-cell-style-name="ce8" table:number-columns-repeated="2"/>
+ <table:table-column table:number-columns-repeated="16382"/>
+ <table:table-row>
+ <table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell>
+ <table:table-cell/>
+ <table:table-cell table:number-columns-repeated="16382"/>
+ </table:table-row>
+ <table:table-row table:number-rows-repeated="1048575">
+ <table:table-cell table:style-name="ce8" table:number-columns-repeated="2"/>
+ <table:table-cell table:number-columns-repeated="16382"/>
+ </table:table-row>
+ </table:table>
+ """;
+
+ private const string OdsSettings =
+ $"""
+ <office:document-settings {OdsBuilder.Namespaces} office:version="1.3"><office:settings>
+ <config:config-item-set config:name="ooo:view-settings"><config:config-item-map-indexed config:name="Views"><config:config-item-map-entry>
+ <config:config-item-map-named config:name="Tables">
+ <config:config-item-map-entry config:name="색칠">
+ <config:config-item config:name="VerticalSplitMode" config:type="short">2</config:config-item>
+ <config:config-item config:name="VerticalSplitPosition" config:type="int">1</config:config-item>
+ </config:config-item-map-entry>
+ </config:config-item-map-named>
+ </config:config-item-map-entry></config:config-item-map-indexed></config:config-item-set>
+ </office:settings></office:document-settings>
+ """;
+
+ private string SalesOds(string folder) =>
+ OdsBuilder.Save(Path.Combine(folder, "매출보고.ods"), OdsAutomaticStyles, OdsTables, OdsStyles, OdsSettings);
+
+ [Fact]
+ public void Ods_repeats_spans_values_and_styles_are_read_like_calc_shows_them()
+ {
+ var book = OdsReader.Read(SalesOds(fx.NewFolder()));
+
+ Assert.Equal(["매출", "색칠"], book.Sheets.Select(s => s.Name)); // the hidden sheet is left out
+ var sales = book.Sheets[0];
+ Assert.Equal(6, sales.Rows.Keys.Max()); // the million empty rows at the end are not expanded
+ Assert.Equal(3, sales.Rows.Values.Max(r => r.Keys.Max()));
+
+ var title = sales.Get(0, 0)!;
+ Assert.Equal("지점별 매출", title.Text);
+ Assert.Equal((true, 14.0, "#FFFFFF", "#1F4E79"), (title.Style.Bold, title.Style.FontSize, title.Style.Color, title.Style.Fill));
+ Assert.Equal((CellAlign.Center, CellVerticalAlign.Center), (title.Style.Align, title.Style.VerticalAlign));
+ Assert.Equal(new CellBorder("thin", "#000000"), title.Style.Bottom);
+ Assert.Equal(new CellRange(0, 0, 0, 2), Assert.Single(sales.Merges));
+
+ void Is(int row, int column, string text, double? value, string? format)
+ {
+ var cell = sales.Get(row, column)!;
+ Assert.Equal((text, value, format, value is not null), (cell.Text, cell.Value, cell.NumberFormat, cell.IsNumber));
+ }
+ Is(1, 0, "1,234.50", 1234.5, "#,##0.00");
+ Is(1, 1, "12.8%", 0.128, "0.0%");
+ Is(1, 2, "-₩5,000", -5000, "\"₩\"#,##0;[Red]-\"₩\"#,##0");
+ Is(2, 0, "2026년 10월 1일", October1, "yyyy\"년 \"m\"월 \"d\"일\"");
+ Is(2, 1, "13:30", 13.5 / 24, "hh:mm");
+ Is(2, 3, "#DIV/0!", null, null);
+ Assert.Equal(("TRUE", true, 1.0), (sales.Get(2, 2)!.Text, sales.Get(2, 2)!.IsBoolean, sales.Get(2, 2)!.Value));
+ Assert.All(from r in new[] { 3, 4 } from c in new[] { 0, 1, 2 } select sales.Get(r, c), cell => Assert.Equal(7, cell!.Value));
+
+ var text = sales.Get(6, 0)!;
+ Assert.Equal(" 앞 공백 세 칸\t탭\n줄\n둘째 문단", text.Text); // the comment is not part of the text
+ Assert.Equal((true, true, true, true, 10.0), (text.Style.Italic, text.Style.Underline, text.Style.Strike, text.Style.Wrap, text.Style.FontSize));
+ Assert.Equal(new CellBorder("double", "#C00000"), text.Style.Bottom);
+
+ Assert.Equal([5], sales.HiddenRows);
+ Assert.Equal([3], sales.HiddenColumns);
+ Assert.Equal(30, Assert.Single(sales.RowHeights).Value); // rows sized to their content have no custom height
+ Assert.Equal([0, 1, 2, 3], sales.ColumnWidths.Keys.Order());
+ Assert.Equal(72 / 5.25, sales.ColumnWidth(0), 3); // 2.54 cm
+ Assert.Equal(57.6 / 5.25, sales.ColumnWidth(1), 3); // 0.8 in
+ Assert.Equal(72 / 5.25, sales.DefaultColumnWidth, 3);
+ Assert.Equal(1, sales.FrozenRows); // table:table-header-rows
+
+ var painted = book.Sheets[1];
+ Assert.Equal(1, painted.FrozenRows); // from settings.xml
+ var row = Assert.Single(painted.Rows).Value; // the formatted rest of the sheet is not content
+ Assert.Equal("#FFFF00", row[1].Style.Fill); // the column's default cell style
+ }
+
+ [Fact]
+ public async Task Ods_to_csv_writes_what_calc_shows()
+ {
+ var outputs = await ConvertAsync(SalesOds(fx.NewFolder()), "csv");
+
+ Assert.Equal(["매출보고_매출.csv", "매출보고_색칠.csv"], outputs.Select(Path.GetFileName));
+ Assert.Equal(
+ "지점별 매출,,\r\n" +
+ "\"1,234.50\",12.8%,\"-₩5,000\"\r\n" +
+ "2026년 10월 1일,13:30,TRUE\r\n" +
+ "7,7,7\r\n" +
+ "7,7,7\r\n" +
+ "\" 앞 공백 세 칸\t탭\n줄\n둘째 문단\",,\r\n", // hidden row and column left out
+ (await File.ReadAllTextAsync(outputs[0], TestContext.Current.CancellationToken)).TrimStart(''));
+ }
+
+ [Fact]
+ public async Task Password_protected_ods_fails_with_a_clear_message()
+ {
+ var path = OdsBuilder.Save(Path.Combine(fx.NewFolder(), "잠금.ods"), "", "<table:table table:name=\"A\"/>", encrypted: true);
+
+ Assert.Contains("password", Assert.Throws<InvalidDataException>(() => OdsReader.Read(path)).Message);
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "csv" });
+ Assert.Contains("password", Assert.Single(job.Files).ErrorDetail);
+ }
+
+ [Fact]
+ public async Task Xlsx_to_ods_and_back_keeps_values_formats_merges_and_widths()
+ {
+ var dir = fx.NewFolder();
+ var xlsx = OfficeTests.SalesWorkbook(dir);
+ var source = XlsxReader.Read(xlsx);
+
+ var ods = Assert.Single(await ConvertAsync(xlsx, "ods"));
+
+ using (var zip = ZipFile.OpenRead(ods))
+ {
+ // OpenDocument: "mimetype" first and stored, so the type can be read at a fixed offset.
+ var mimetype = zip.Entries[0];
+ Assert.Equal(("mimetype", mimetype.Length), (mimetype.FullName, mimetype.CompressedLength));
+ using (var reader = new StreamReader(mimetype.Open()))
+ Assert.Equal("application/vnd.oasis.opendocument.spreadsheet", await reader.ReadToEndAsync(TestContext.Current.CancellationToken));
+ Assert.NotNull(zip.GetEntry("META-INF/manifest.xml"));
+
+ XElement content;
+ using (var stream = zip.GetEntry("content.xml")!.Open())
+ content = XElement.Load(stream);
+ var cells = content.Descendants(Table + "table-cell").ToList();
+ // Numbers are numbers with a data style; text:p is the text Excel showed.
+ var won = cells.Single(c => (string?)c.Attribute(Office + "value") == "1350000");
+ Assert.Equal(("float", "1,350,000원"), ((string?)won.Attribute(Office + "value-type"), won.Element(Text + "p")!.Value));
+ var dataStyle = content.Descendants().Single(e => (string?)e.Attribute(Style + "name") == (string?)content.Descendants(Style + "style")
+ .Single(s => (string?)s.Attribute(Style + "name") == (string?)won.Attribute(Table + "style-name")).Attribute(Style + "data-style-name"));
+ Assert.Equal("원", dataStyle.Element(Number + "text")!.Value);
+ Assert.Contains(cells, c => (string?)c.Attribute(Office + "date-value") == "2026-10-01" && (string?)c.Attribute(Office + "value-type") == "date");
+ Assert.Contains(cells, c => (string?)c.Attribute(Office + "value-type") == "percentage" && (string?)c.Attribute(Office + "value") == "0.128");
+ Assert.Equal("4", (string?)cells.First(c => c.Value == "지점별 매출").Attribute(Table + "number-columns-spanned"));
+ Assert.DoesNotContain("보이면 안 됨", content.Value);
+ }
+
+ var fromOds = OdsReader.Read(ods);
+ AssertSameCells(source, fromOds);
+ AssertSameLayout(source, fromOds);
+ var header = fromOds.Sheets[0].Get(1, 0)!.Style;
+ Assert.Equal((true, "#FFFFFF", "#1F4E79", CellAlign.Center, "thin"), (header.Bold, header.Color, header.Fill, header.Align, header.Bottom.Style));
+
+ File.Move(ods, Path.Combine(dir, "사본.ods"));
+ var back = Assert.Single(await ConvertAsync(Path.Combine(dir, "사본.ods"), "xlsx"));
+ var result = XlsxReader.Read(back);
+ AssertSameCells(source, result);
+ AssertSameLayout(source, result);
+ Assert.Equal("#1F4E79", result.Sheets[0].Get(1, 0)!.Style.Fill);
+ }
+
+ [Theory]
+ [InlineData("0", "float")]
+ [InlineData("0.00", "float")]
+ [InlineData("#,##0", "float")]
+ [InlineData("#,##0.00", "float")]
+ [InlineData("0.0##", "float")]
+ [InlineData("#,##0,", "float")]
+ [InlineData("#,##0\"원\"", "float")]
+ [InlineData("$#,##0.00", "float")]
+ [InlineData("#,##0;[Red]-#,##0", "float")]
+ [InlineData("#,##0.00;(#,##0.00);-", "float")]
+ [InlineData("0%", "percentage")]
+ [InlineData("0.0%", "percentage")]
+ [InlineData("0.00E+00", "float")]
+ [InlineData("yyyy-mm-dd", "date")]
+ [InlineData("d-mmm-yy", "date")]
+ [InlineData("yyyy-mm-dd h:mm", "date")]
+ [InlineData("dddd, mmmm d", "date")]
+ [InlineData("h:mm AM/PM", "time")]
+ [InlineData("mm:ss", "time")]
+ [InlineData("mmss.0", "time")]
+ [InlineData("[h]:mm:ss", "time")]
+ public void Excel_number_formats_survive_opendocument_data_styles(string code, string valueType)
+ {
+ var (xml, type) = OdsNumberStyles.ToOdf(code, "N1")!.Value;
+ // Like OdsReader: a space alone in number:text is meaningful.
+ var styles = XElement.Parse($"<styles {OdsBuilder.Namespaces}>{xml}</styles>", LoadOptions.PreserveWhitespace)
+ .Elements().ToDictionary(e => (string)e.Attribute(Style + "name")!);
+
+ Assert.Equal(valueType, type);
+ Assert.Equal(code, OdsNumberStyles.ToExcel(styles["N1"], styles.GetValueOrDefault));
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("General")]
+ [InlineData("@")]
+ [InlineData("[>=100]0;0.0")]
+ [InlineData("# ?/?")]
+ [InlineData("000-0000")]
+ public void Excel_formats_without_a_data_style_stay_plain_numbers(string? code) =>
+ Assert.Null(OdsNumberStyles.ToOdf(code, "N1"));
+
+ private static void AssertSameCells(Workbook expected, Workbook actual)
+ {
+ Assert.Equal(expected.Sheets.Select(s => s.Name), actual.Sheets.Select(s => s.Name));
+ foreach (var (want, got) in expected.Sheets.Zip(actual.Sheets))
+ {
+ foreach (var (row, cells) in want.Rows)
+ {
+ foreach (var (column, cell) in cells)
+ {
+ var other = got.Get(row, column);
+ Assert.True(other is not null, $"{want.Name} R{row + 1}C{column + 1} is missing");
+ Assert.Equal((cell.Text, cell.IsNumber, cell.Value, cell.NumberFormat, cell.IsBoolean),
+ (other.Text, other.IsNumber, other.Value, other.NumberFormat, other.IsBoolean));
+ }
+ }
+ }
+ }
+
+ private static void AssertSameLayout(Workbook expected, Workbook actual)
+ {
+ foreach (var (want, got) in expected.Sheets.Zip(actual.Sheets))
+ {
+ Assert.Equal(want.Merges, got.Merges);
+ Assert.Equal(want.FrozenRows, got.FrozenRows);
+ foreach (var column in want.ColumnWidths.Keys)
+ Assert.Equal(want.ColumnWidth(column), got.ColumnWidth(column), 2);
+ }
+ }
+
+ // ───────────────────────── TSV ─────────────────────────
+
+ [Fact]
+ public async Task Tsv_to_xlsx_and_back_keeps_every_value()
+ {
+ var dir = fx.NewFolder();
+ // Commas are data in TSV: "1,200" and "Lee, J" stay one field each.
+ const string Tsv = "이름\t금액\t메모\r\n김민지\t1,200\t\"줄\n바꿈\"\r\nLee, J\t3.5\t\"\"\"인용\"\"\"\r\n";
+ var tsv = Path.Combine(dir, "명단.tsv");
+ await File.WriteAllTextAsync(tsv, Tsv, TestContext.Current.CancellationToken);
+
+ var xlsx = Assert.Single(await ConvertAsync(tsv, "xlsx"));
+ var sheet = Assert.Single(XlsxReader.Read(xlsx).Sheets);
+ Assert.Equal(("1,200", false), (sheet.Get(1, 1)!.Text, sheet.Get(1, 1)!.IsNumber));
+ Assert.Equal(("Lee, J", 3.5), (sheet.Get(2, 0)!.Text, sheet.Get(2, 1)!.Value));
+ Assert.Equal("줄\n바꿈", sheet.Get(1, 2)!.Text);
+
+ File.Move(xlsx, Path.Combine(dir, "사본.xlsx"));
+ var back = Assert.Single(await ConvertAsync(Path.Combine(dir, "사본.xlsx"), "tsv"));
+ var bytes = await File.ReadAllBytesAsync(back, TestContext.Current.CancellationToken);
+ Assert.Equal([0xEF, 0xBB, 0xBF], bytes[..3]);
+ Assert.Equal(Tsv, Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3));
+
+ var csv = Assert.Single(await ConvertAsync(tsv, "csv"));
+ Assert.StartsWith("이름,금액,메모\r\n김민지,\"1,200\",", (await File.ReadAllTextAsync(csv, TestContext.Current.CancellationToken)).TrimStart(''));
+ }
+
+ [Fact]
+ public async Task Workbook_to_tsv_writes_one_file_per_sheet()
+ {
+ var outputs = await ConvertAsync(OfficeTests.SalesWorkbook(fx.NewFolder()), "tsv");
+
+ Assert.Equal(["매출보고_매출.tsv", "매출보고_메모.tsv", "매출보고_넓은 표.tsv"], outputs.Select(Path.GetFileName));
+ Assert.StartsWith("지점별 매출\t\t\t\r\n지점\t매출\t일자\t성장률\r\n서울 강남\t1,350,000원\t2026-10-01\t12.8%\r\n",
+ (await File.ReadAllTextAsync(outputs[0], TestContext.Current.CancellationToken)).TrimStart(''));
+ }
+
+ // ───────────────────────── PDF ─────────────────────────
+
+ [Theory]
+ [InlineData("xls")]
+ [InlineData("ods")]
+ [InlineData("tsv")]
+ public async Task Spreadsheets_to_pdf_without_libreoffice(string format)
+ {
+ Assert.SkipUnless(fx.Converters.Any(c => c.Id == "rhwp" && fx.Catalog.StatusOf(c).IsAvailable), "rhwp not found");
+ var dir = fx.NewFolder();
+ var input = format switch
+ {
+ "xls" => SalesXls(dir),
+ "ods" => SalesOds(dir),
+ _ => Path.Combine(dir, "표.tsv"),
+ };
+ if (format == "tsv")
+ await File.WriteAllTextAsync(input, "항목\t값\r\n가\t1\r\n", TestContext.Current.CancellationToken);
+
+ var pdf = Assert.Single(await ConvertAsync(input, "pdf"));
+
+ // PDFium (for counting pages) is only known to the platform analyzer on desktop and mobile systems.
+ if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() || OperatingSystem.IsLinux())
+ Assert.True(PDFtoImage.Conversion.GetPageCount(await File.ReadAllBytesAsync(pdf, TestContext.Current.CancellationToken)) > 0);
+ }
+
+ // ───────────────────────── Routes ─────────────────────────
+
+ [Theory]
+ [InlineData("xls", "xlsx", "spreadsheet")]
+ [InlineData("xls", "ods", "spreadsheet")]
+ [InlineData("xls", "csv", "spreadsheet")]
+ [InlineData("xls", "tsv", "spreadsheet")]
+ [InlineData("ods", "xlsx", "spreadsheet")]
+ [InlineData("ods", "csv", "spreadsheet")]
+ [InlineData("xlsx", "ods", "spreadsheet")]
+ [InlineData("xlsx", "tsv", "spreadsheet")]
+ [InlineData("csv", "ods", "spreadsheet")]
+ [InlineData("csv", "tsv", "spreadsheet")]
+ [InlineData("tsv", "xlsx", "spreadsheet")]
+ [InlineData("tsv", "ods", "spreadsheet")]
+ [InlineData("xls", "hwpx", "hwpx-writer")]
+ [InlineData("ods", "hwpx", "hwpx-writer")]
+ [InlineData("tsv", "hwpx", "hwpx-writer")]
+ [InlineData("xls", "pdf", "hwpx-writer,rhwp")]
+ [InlineData("ods", "pdf", "hwpx-writer,rhwp")]
+ [InlineData("tsv", "pdf", "hwpx-writer,rhwp")]
+ public void Spreadsheets_convert_without_libreoffice(string from, string to, string engines)
+ {
+ Assert.Equal(engines.Split(','), BuiltInPlanner("rhwp").Plan(from, to)!.Steps.Select(s => s.Converter.Id));
+ // Built-in conversions win even when LibreOffice is installed.
+ Assert.DoesNotContain(fx.Catalog.CreatePlanner(["libreoffice", "rhwp"]).Plan(from, to)!.Steps, s => s.Converter.Id == "libreoffice");
+ }
+
+ [Fact]
+ public void Spreadsheet_engine_has_no_same_format_edges()
+ {
+ var engine = fx.Converters.OfType<SpreadsheetConverter>().Single();
+ Assert.DoesNotContain(engine.Edges, e => e.From == e.To);
+ Assert.DoesNotContain(engine.Edges, e => e.To == "xls"); // XLS is read only; writing it needs LibreOffice
+ }
+
+ // ───────────────────────── LibreOffice cross-check ─────────────────────────
+
+ [Fact]
+ public async Task LibreOffice_reads_our_ods_and_we_read_its_ods_and_xls()
+ {
+ var libreOffice = fx.Converters.Single(c => c.Id == "libreoffice");
+ Assert.SkipUnless(fx.Catalog.StatusOf(libreOffice).IsAvailable, "LibreOffice not installed");
+ var dir = fx.NewFolder();
+ var xlsx = OfficeTests.SalesWorkbook(dir);
+ var ods = Assert.Single(await ConvertAsync(xlsx, "ods"));
+
+ var books = new Dictionary<string, Workbook>
+ {
+ ["our ODS opened by LibreOffice"] = XlsxReader.Read(await LibreOfficeAsync(libreOffice, ods, "ods", "xlsx")),
+ ["ODS by LibreOffice"] = OdsReader.Read(await LibreOfficeAsync(libreOffice, xlsx, "xlsx", "ods")),
+ ["XLS by LibreOffice"] = XlsReader.Read(await LibreOfficeAsync(libreOffice, xlsx, "xlsx", "xls")),
+ };
+ foreach (var (name, book) in books)
+ {
+ var sales = book.Sheets[0];
+ Assert.True(new[] { "매출", "메모", "넓은 표" }.SequenceEqual(book.Sheets.Select(s => s.Name)), name);
+ Assert.True(sales.Get(2, 1)!.Text == "1,350,000원", $"{name}: {sales.Get(2, 1)!.Text}");
+ Assert.True(sales.Get(2, 3)!.Text == "12.8%", $"{name}: {sales.Get(2, 3)!.Text}");
+ // LibreOffice shows built-in dates in its own locale's order: compare the value.
+ Assert.True(sales.Get(2, 2)!.Value == October1, $"{name}: {sales.Get(2, 2)!.Value}");
+ Assert.True(sales.Get(4, 1)!.Text == "2,220,000원", $"{name}: {sales.Get(4, 1)!.Text}");
+ Assert.True(new CellRange(0, 0, 0, 3) == Assert.Single(sales.Merges), name);
+ Assert.True(sales.Get(1, 0)!.Style.Align == CellAlign.Center, name);
+ // LibreOffice measures character widths with its own fonts, so widths through ODS move by up to a fifth;
+ // XLS keeps Excel's own unit.
+ var tolerance = name.StartsWith("XLS", StringComparison.Ordinal) ? 0.01 : 0.25;
+ Assert.True(Math.Abs(sales.ColumnWidth(0) - 14) <= 14 * tolerance, $"{name}: {sales.ColumnWidth(0)}");
+ Assert.True(Math.Abs(sales.ColumnWidth(0) / sales.ColumnWidth(1) - 14.0 / 12) < 0.02, $"{name}: {sales.ColumnWidth(0)} / {sales.ColumnWidth(1)}");
+ }
+ }
+
+ private async Task<string> LibreOfficeAsync(IConverter libreOffice, string input, string from, string to)
+ {
+ var output = Path.Combine(Path.GetDirectoryName(input)!, $"{Path.GetFileNameWithoutExtension(input)}.lo-{from}.{to}");
+ var written = await libreOffice.ConvertAsync(new ConversionStep(input, from, to, new Preset(), new FixedPath(output), fx.NewFolder()),
+ null, TestContext.Current.CancellationToken);
+ return written.Single();
+ }
+
+ private sealed class FixedPath(string path) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => path;
+ }
+}