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.

Repeat an Excel sheet's print title rows on every PDF page (#407)

cre8ive-marketingeda4b53ecf0a
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 3ba038b0..482c302e 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -311,7 +311,8 @@ Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) an
- Word's document grid ("lines"), which 한글 does not have, as an "at least" line spacing.
- **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,
+ borders, alignment and merged cells; an XLSX's rows to repeat at the top (Print Titles, #407), else frozen top
+ rows, repeat on every page, and rows above the print titles come once before them. 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
Excel's "Fit all columns on one page". CSV is read with its delimiter (comma, semicolon, tab) and encoding
(UTF-8 / UTF-16 with BOM, else CP949 as saved by Korean Excel). Not converted: charts, pictures, conditional
@@ -384,7 +385,7 @@ 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 |
+| XLSX | own reader: values, number formats, fonts, fills, borders, alignment, merges, widths, heights, hidden rows / columns / sheets, frozen rows, print titles (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 |
diff --git a/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
index 179ee136..8f437a7d 100644
--- a/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
@@ -3,7 +3,7 @@
//
// Layout choices, since a sheet has no page of its own: A4 with narrow margins, landscape when the columns are much
// wider than a portrait page, columns (and text) scaled down to fit the width like "Fit all columns on one page",
-// light grey grid lines where cells have no border, frozen top rows repeated on every page.
+// light grey grid lines where cells have no border, the rows to repeat at the top (or frozen top rows) on every page.
using Filee.Engines.Office.Sheets;
@@ -66,10 +66,15 @@ internal static class SheetDocument
section.Blocks.Add(title);
}
- // Page breaks set in Excel start a new table on a new page; frozen header rows repeat at its top.
- var headerRows = sheet.FrozenRows is > 0 and <= 5 ? sheet.FrozenRows : 0;
- var header = rows.Where(r => r < headerRows).ToList();
- var body = rows.Where(r => r >= headerRows).ToList();
+ // Page breaks set in Excel start a new table on a new page; the rows to repeat at the top (Print Titles, else
+ // frozen header rows) repeat at its top. Rows above print titles (a document title) come once, before them.
+ var titles = sheet.TitleRows ?? (sheet.FrozenRows is > 0 and <= 5 ? (0, sheet.FrozenRows - 1) : null);
+ var headerRows = titles is { } t ? rows.Where(r => r >= t.First && r <= t.Last).ToHashSet() : [];
+ var lead = titles is { } above ? rows.Where(r => r < above.First).ToList() : [];
+ var header = rows.Where(headerRows.Contains).ToList();
+ var body = rows.Where(r => !headerRows.Contains(r) && (titles is not { } u || r > u.Last)).ToList();
+ if (lead.Count > 0)
+ section.Blocks.Add(Table(sheet, lead, columns, [], fontScale, widths.Select(w => Math.Max(300, (int)(w * scale))).ToArray()));
var pages = new List<List<int>> { new(header) };
var previous = -1;
foreach (var r in body)
@@ -99,7 +104,7 @@ internal static class SheetDocument
}
/// <summary>One table of the given rows (one printed page or more), merged areas cut at its first and last row.</summary>
- private static HTable Table(Worksheet sheet, List<int> rows, List<int> columns, int headerRows, double fontScale, int[] widths)
+ private static HTable Table(Worksheet sheet, List<int> rows, List<int> columns, HashSet<int> headerRows, double fontScale, int[] widths)
{
var table = new HTable
{
@@ -130,7 +135,7 @@ internal static class SheetDocument
{
var row = new HRow
{
- Header = r < headerRows,
+ Header = headerRows.Contains(r),
Height = sheet.RowHeights.TryGetValue(r, out var points) ? (int)(points * 100 * fontScale) : null,
};
foreach (var c in columns)
diff --git a/src/Filee.Engines/Office/Sheets/Workbook.cs b/src/Filee.Engines/Office/Sheets/Workbook.cs
index b00d0689..6a579d04 100644
--- a/src/Filee.Engines/Office/Sheets/Workbook.cs
+++ b/src/Filee.Engines/Office/Sheets/Workbook.cs
@@ -34,6 +34,12 @@ internal sealed class Worksheet(string name)
/// <summary>Rows frozen at the top (usually headers): repeated on every printed page.</summary>
public int FrozenRows { get; set; }
+ /// <summary>
+ /// 0-based rows to repeat at the top of every printed page (Page Layout → Print Titles), or null. They win over
+ /// <see cref="FrozenRows"/> and need not start at the top.
+ /// </summary>
+ public (int First, int Last)? TitleRows { get; set; }
+
/// <summary>0-based rows that start a new printed page (page breaks set in Excel: Page Layout → Breaks).</summary>
public SortedSet<int> RowBreaks { get; } = [];
diff --git a/src/Filee.Engines/Office/Sheets/XlsxReader.cs b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
index 713ae38d..cd663147 100644
--- a/src/Filee.Engines/Office/Sheets/XlsxReader.cs
+++ b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
@@ -5,6 +5,7 @@
using System.Globalization;
using System.Text;
+using System.Text.RegularExpressions;
using System.Xml.Linq;
using Filee.Engines.Office.Ooxml;
@@ -46,19 +47,51 @@ internal sealed class XlsxReader
if (_package.TargetOfType(workbookPath, "/styles") is { } styles)
ReadStyles(_package.Part(styles), colors);
+ // Print titles are a defined name per sheet, by the sheet's position (hidden sheets count).
+ var titles = new Dictionary<int, (int, int)>();
+ foreach (var name in workbook.Element(S + "definedNames")?.Elements(S + "definedName") ?? [])
+ {
+ if ((string?)name.Attribute("name") == "_xlnm.Print_Titles" && int.TryParse((string?)name.Attribute("localSheetId"), out var id)
+ && PrintTitleRows(name.Value) is { } rows)
+ titles[id] = rows;
+ }
+
var result = new Workbook();
+ var index = -1;
foreach (var sheet in workbook.Element(S + "sheets")?.Elements(S + "sheet") ?? [])
{
+ index++;
if ((string?)sheet.Attribute("state") is "hidden" or "veryHidden")
continue;
var target = _package.Target(workbookPath, (string?)sheet.Attribute(R + "id"));
if (target is null || _package.Part(target)?.Root is not { } xml || xml.Name != S + "worksheet")
continue; // chart sheets and dialog sheets have no cells
- result.Sheets.Add(ReadSheet((string?)sheet.Attribute("name") ?? "Sheet", xml));
+ var read = ReadSheet((string?)sheet.Attribute("name") ?? "Sheet", xml);
+ if (titles.TryGetValue(index, out var titleRows))
+ read.TitleRows = titleRows;
+ result.Sheets.Add(read);
}
return result;
}
+ /// <summary>
+ /// The 0-based rows of a print titles reference: <c>'Bill of quantities'!$3:$4</c>, also next to repeated columns
+ /// (<c>Sheet1!$A:$B,Sheet1!$1:$2</c>); null when it repeats columns only.
+ /// </summary>
+ internal static (int First, int Last)? PrintTitleRows(string reference)
+ {
+ foreach (var part in reference.Split(','))
+ {
+ var match = PrintTitleRowsPattern.Match(part[(part.LastIndexOf('!') + 1)..].Trim());
+ if (match.Success && int.TryParse(match.Groups[1].Value, out var first) && int.TryParse(match.Groups[2].Value, out var last)
+ && first >= 1 && last >= first)
+ return (first - 1, last - 1);
+ }
+ return null;
+ }
+
+ private static readonly Regex PrintTitleRowsPattern = new(@"^\$?(\d+):\$?(\d+)$", RegexOptions.CultureInvariant);
+
private void ReadSharedStrings(XDocument? xml)
{
foreach (var item in xml?.Root?.Elements(S + "si") ?? [])
diff --git a/tests/Filee.Engines.Tests/OfficeBuilders.cs b/tests/Filee.Engines.Tests/OfficeBuilders.cs
index 60fcb11a..fe5d8591 100644
--- a/tests/Filee.Engines.Tests/OfficeBuilders.cs
+++ b/tests/Filee.Engines.Tests/OfficeBuilders.cs
@@ -103,6 +103,9 @@ internal sealed class XlsxBuilder
return this;
}
+ /// <summary>A <c>definedNames</c> element for the workbook (print titles, print areas), or empty.</summary>
+ public string DefinedNames { get; set; } = "";
+
public string Save(string path)
{
var parts = new Dictionary<string, string>
@@ -110,7 +113,7 @@ internal sealed class XlsxBuilder
["_rels/.rels"] = OpcWriter.Relationships([("rId1", "officeDocument", "xl/workbook.xml")]),
["xl/workbook.xml"] = $"<workbook {Namespaces}><sheets>" +
string.Concat(_sheets.Select((s, i) => $"<sheet name=\"{OpcWriter.Escape(s.Name)}\" sheetId=\"{i + 1}\"{(s.Hidden ? " state=\"hidden\"" : "")} r:id=\"rId{i + 1}\"/>")) +
- "</sheets></workbook>",
+ "</sheets>" + DefinedNames + "</workbook>",
["xl/_rels/workbook.xml.rels"] = OpcWriter.Relationships(
_sheets.Select((_, i) => ($"rId{i + 1}", "worksheet", $"worksheets/sheet{i + 1}.xml"))
.Append(("rIdS", "sharedStrings", "sharedStrings.xml"))
diff --git a/tests/Filee.Engines.Tests/OfficeTests.cs b/tests/Filee.Engines.Tests/OfficeTests.cs
index 28b7981b..5ff535cb 100644
--- a/tests/Filee.Engines.Tests/OfficeTests.cs
+++ b/tests/Filee.Engines.Tests/OfficeTests.cs
@@ -6,6 +6,7 @@ using System.Text;
using System.Xml.Linq;
using Filee.Core.Conversion;
using Filee.Core.Presets;
+using Filee.Engines.Hwp.Hwpx;
using Filee.Engines.Office.Sheets;
using ImageMagick;
using static Filee.Engines.Tests.HwpxAssert;
@@ -168,6 +169,42 @@ public class OfficeTests(EngineFixture fx) : IClassFixture<EngineFixture>
RenderWithRhwp(fx, hwpx, "xlsx-sales");
}
+ [Fact]
+ public void Print_titles_name_the_rows_they_repeat()
+ {
+ Assert.Equal((2, 3), XlsxReader.PrintTitleRows("'공사 내역서'!$3:$4"));
+ Assert.Equal((0, 1), XlsxReader.PrintTitleRows("Sheet1!$A:$B,Sheet1!$1:$2"));
+ Assert.Null(XlsxReader.PrintTitleRows("Sheet1!$A:$B")); // columns only
+ }
+
+ [Fact]
+ public async Task Rows_to_repeat_at_the_top_repeat_on_every_page_of_a_pdf_bound_table()
+ {
+ // Issue #407: a bill of quantities with a title, then two heading rows set as "Rows to repeat at top" and a
+ // page break. The title comes once; the headings start every page's table.
+ var xlsx = new XlsxBuilder();
+ xlsx.Sheet("숨김", Row(1, xlsx.Text("A1", "x")), hidden: true); // hidden sheets still count in localSheetId
+ var rows = Row(1, xlsx.Text("A1", "공사 내역서", Header)) + Row(2, xlsx.Text("A2", "현장: 서울")) +
+ Row(3, xlsx.Text("A3", "품명", Header), xlsx.Text("B3", "금액", Header)) +
+ Row(4, xlsx.Text("A4", "규격", Header), xlsx.Text("B4", "원", Header)) +
+ string.Concat(Enumerable.Range(5, 40).Select(r => Row(r, xlsx.Text($"A{r}", $"자재 {r}"), Number($"B{r}", r * 1000))));
+ xlsx.Sheet("내역", rows, after: "<rowBreaks count=\"1\" manualBreakCount=\"1\"><brk id=\"24\" max=\"16383\" man=\"1\"/></rowBreaks>");
+ xlsx.DefinedNames = "<definedNames><definedName name=\"_xlnm.Print_Titles\" localSheetId=\"1\">내역!$3:$4</definedName></definedNames>";
+ var path = xlsx.Save(Path.Combine(fx.NewFolder(), "내역서.xlsx"));
+
+ Assert.Equal((2, 3), Assert.Single(XlsxReader.Read(path).Sheets).TitleRows);
+ var tables = SheetDocument.Build(XlsxReader.Read(path)).Sections.Single().Blocks.OfType<HTable>().ToList();
+
+ Assert.Equal(3, tables.Count); // the title, then one table per printed page
+ Assert.Equal(2, tables[0].Rows.Count);
+ Assert.DoesNotContain(tables[0].Rows, r => r.Header);
+ foreach (var page in tables.Skip(1))
+ Assert.Equal([true, true, false], page.Rows.Take(3).Select(r => r.Header));
+ Assert.Equal(2 + 20, tables[1].Rows.Count); // rows 5-24, then the break
+ Assert.Equal(2 + 20, tables[2].Rows.Count); // rows 25-44
+ Assert.True(tables[2].PageBreakBefore);
+ }
+
// ───────────────────────── Presentations ─────────────────────────
private static byte[] Png()