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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 20 additions & 22 deletions src/MiniPdf/ExcelReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@
if (!string.IsNullOrEmpty(targetMode) && !string.Equals(targetMode, "Internal", StringComparison.OrdinalIgnoreCase)) continue;
if (type?.EndsWith("/worksheet", StringComparison.OrdinalIgnoreCase) != true) continue;

result[id] = ResolveRelationshipTarget("xl", target);

Check warning on line 288 in src/MiniPdf/ExcelReader.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'target' in 'string ExcelReader.ResolveRelationshipTarget(string sourceDirectory, string target)'.

Check warning on line 288 in src/MiniPdf/ExcelReader.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'string Dictionary<string, string>.this[string key]'.
}

return result;
Expand Down Expand Up @@ -423,7 +423,7 @@
var color = ResolveColorElement(el.Element(ns + "color"), themeColors);
// Default border color is black
color ??= PdfColor.FromRgb(0, 0, 0);
return new BorderSide(style, color);

Check warning on line 426 in src/MiniPdf/ExcelReader.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'Style' in 'BorderSide.BorderSide(string Style, PdfColor? Color)'.
}

/// <summary>
Expand Down Expand Up @@ -478,7 +478,7 @@
if (int.TryParse(wholeTable.Attribute("dxfId")?.Value, out var dxfId) &&
dxfId >= 0 && dxfId < dxfBorders.Count && dxfBorders[dxfId] != null)
{
result[name] = dxfBorders[dxfId]!;

Check warning on line 481 in src/MiniPdf/ExcelReader.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'CellBorderInfo Dictionary<string, CellBorderInfo>.this[string key]'.
}
}

Expand Down Expand Up @@ -528,9 +528,9 @@
}

if (string.IsNullOrEmpty(refAttr) || string.IsNullOrEmpty(styleName)) continue;
if (!tableStyleBorders.TryGetValue(styleName, out var tableBorder)) continue;

Check warning on line 531 in src/MiniPdf/ExcelReader.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'key' in 'bool Dictionary<string, CellBorderInfo>.TryGetValue(string key, out CellBorderInfo value)'.

var rangeParts = refAttr.Split(':');

Check warning on line 533 in src/MiniPdf/ExcelReader.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
if (rangeParts.Length != 2) continue;

var (startRow, startCol) = ParseCellRef(rangeParts[0]);
Expand Down Expand Up @@ -733,7 +733,11 @@
}
}

// Data rows: apply wholeTable fill and row stripe banding
// Data rows: layer the wholeTable element, row stripes, the table's
// data format, each column's data format, then the firstColumn
// element. Each layer adds to the ones before it. A fill set on the
// cell itself is direct formatting, so it is restored after the
// table layers.
var dataStart = startRow + headerRowCount;
var dataEnd = totalsRowCount > 0 ? endRow - totalsRowCount : endRow;
var directDataStyle = GetDxfStyle(dxfInfos, dataDxf);
Expand All @@ -747,9 +751,10 @@
for (var c = startCol; c <= endCol && c < rows[r].Count; c++)
{
var cell = rows[r][c];
if (directDataStyle != null) cell = ApplyDxfStyle(cell, directDataStyle);
else if (namedWholeStyle != null) cell = ApplyDxfStyle(cell, namedWholeStyle);
var ownFill = cell.FillColor;
if (namedWholeStyle != null) cell = ApplyDxfStyle(cell, namedWholeStyle);
Comment thread
shps951023 marked this conversation as resolved.
Resolved
if (stripeStyle != null) cell = ApplyDxfStyle(cell, stripeStyle);
if (directDataStyle != null) cell = ApplyDxfStyle(cell, directDataStyle);
Comment thread
shps951023 marked this conversation as resolved.
Resolved

var relativeCol = c - startCol;
if (relativeCol >= 0 && relativeCol < columnDataDxfs.Count &&
Expand All @@ -758,17 +763,12 @@
cell = ApplyDxfStyle(cell, columnDataStyle);
}

rows[r][c] = cell;
}
}
if (c == startCol && showFirstColumn && namedFirstColStyle != null)
cell = ApplyDxfStyle(cell, namedFirstColStyle);

// First column: apply firstColumn DXF style (when showFirstColumn)
if (showFirstColumn && namedFirstColStyle != null)
{
for (var r = dataStart; r <= dataEnd && r < rows.Count; r++)
{
if (startCol < rows[r].Count)
rows[r][startCol] = ApplyDxfStyle(rows[r][startCol], namedFirstColStyle);
if (ownFill != null) cell = cell with { FillColor = ownFill };
Comment thread
shps951023 marked this conversation as resolved.
Resolved

rows[r][c] = cell;
}
}
}
Expand Down Expand Up @@ -914,12 +914,8 @@
{
if (fgPdf != null)
{
var c = fgPdf.Value;
// Skip pure white fills as they're invisible
if (c.R < 0.99f || c.G < 0.99f || c.B < 0.99f)
fills.Add(c);
else
fills.Add(null);
// Preserve explicit white fills so they can override a table-style fill.
fills.Add(fgPdf.Value);
}
else
fills.Add(null);
Expand Down Expand Up @@ -1238,15 +1234,17 @@
{
var patternFill = fillEl.Element(ns + "patternFill");
var patternType = patternFill?.Attribute("patternType")?.Value;
if (!string.Equals(patternType, "none", StringComparison.OrdinalIgnoreCase))
var bgEl = patternFill?.Element(ns + "bgColor");
var fgEl = patternFill?.Element(ns + "fgColor");
var hasFillValue = !string.Equals(patternType, "none", StringComparison.OrdinalIgnoreCase)
&& (!string.IsNullOrWhiteSpace(patternType) || bgEl != null || fgEl != null);
if (hasFillValue)
{
fillSpecified = true;
var bgEl = fillEl.Descendants(ns + "bgColor").FirstOrDefault();
if (bgEl != null)
fillColor = ResolveColorElement(bgEl, themeColors);
if (fillColor == null)
{
var fgEl = fillEl.Descendants(ns + "fgColor").FirstOrDefault();
if (fgEl != null)
fillColor = ResolveColorElement(fgEl, themeColors);
}
Expand Down
221 changes: 221 additions & 0 deletions tests/MiniPdf.Tests/ExcelTableStyleTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
using System.IO.Compression;
using System.Text;

namespace MiniSoftware.Tests;

public class ExcelTableStyleTests
{
[Fact]
public void TableDataFormat_LayersOverWholeTableStyle()
{
// The table carries its own data format (dataDxfId, italic only) and a
// table style whose wholeTable element defines a fill.
using var stream = CreateWorkbookWithStyledTable();

var sheet = Assert.Single(ExcelReader.ReadSheets(stream));

var wholeTableFill = PdfColor.FromRgb(0xDD, 0xF4, 0xF9);
Assert.All(new[] { sheet.Rows[1][0], sheet.Rows[1][1], sheet.Rows[2][0], sheet.Rows[2][1] }, cell =>
{
Assert.Equal(wholeTableFill, cell.FillColor);
Assert.True(cell.Italic);
});
Assert.Null(sheet.Rows[1][2].FillColor);
Assert.False(sheet.Rows[1][2].Italic);
}

[Fact]
public void CellFill_StaysOnTopOfTableStyle()
{
// A4 has its own red fill. B4 in the same row has none.
using var stream = CreateWorkbookWithStyledTable();

var sheet = Assert.Single(ExcelReader.ReadSheets(stream));

Assert.Equal(PdfColor.FromRgb(0xFF, 0x00, 0x00), sheet.Rows[3][0].FillColor);
Assert.True(sheet.Rows[3][0].Italic);
Assert.Equal(PdfColor.FromRgb(0xDD, 0xF4, 0xF9), sheet.Rows[3][1].FillColor);
}

[Fact]
public void CellFill_StaysOnTopOfRowStripeAndFirstColumn()
{
// Rows 2 and 4 are first-stripe rows. A4 has its own red fill.
using var stream = CreateWorkbookWithStyledTable(stripesAndFirstColumn: true);

var sheet = Assert.Single(ExcelReader.ReadSheets(stream));

var stripeFill = PdfColor.FromRgb(0x00, 0xB0, 0x50);
Assert.Equal(stripeFill, sheet.Rows[1][0].FillColor);
Assert.Equal(stripeFill, sheet.Rows[3][1].FillColor);
Assert.Equal(PdfColor.FromRgb(0xFF, 0x00, 0x00), sheet.Rows[3][0].FillColor);
// The firstColumn element still sets the font of a cell that keeps its own fill.
Assert.True(sheet.Rows[1][0].Bold);
Assert.True(sheet.Rows[3][0].Bold);
Assert.False(sheet.Rows[3][1].Bold);
}

[Fact]
public void EmptyDataDxfFill_PreservesRowStripe()
{
using var stream = CreateWorkbookWithStyledTable(stripesAndFirstColumn: true, emptyDataPatternFill: true);

var sheet = Assert.Single(ExcelReader.ReadSheets(stream));

var stripeFill = PdfColor.FromRgb(0x00, 0xB0, 0x50);
Assert.Equal(stripeFill, sheet.Rows[1][0].FillColor);
Assert.Equal(stripeFill, sheet.Rows[1][1].FillColor);
}

[Fact]
public void ExplicitWhiteCellFill_StaysOnTopOfTableStyle()
{
using var stream = CreateWorkbookWithStyledTable();

var sheet = Assert.Single(ExcelReader.ReadSheets(stream));

Assert.Equal(PdfColor.FromRgb(0xFF, 0xFF, 0xFF), sheet.Rows[4][0].FillColor);
Assert.Equal(PdfColor.FromRgb(0xDD, 0xF4, 0xF9), sheet.Rows[4][1].FillColor);
}

private static MemoryStream CreateWorkbookWithStyledTable(bool stripesAndFirstColumn = false, bool emptyDataPatternFill = false)
{
var flag = stripesAndFirstColumn ? "1" : "0";
var dataDxfFill = emptyDataPatternFill ? "<fill><patternFill/></fill>" : string.Empty;
var ms = new MemoryStream();
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))
{
AddEntry(archive, "[Content_Types].xml",
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="xml" ContentType="application/xml"/>
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+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/tables/table1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/>
<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>
</Types>
""");

AddEntry(archive, "_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>
""");

AddEntry(archive, "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"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>
</Relationships>
""");

AddEntry(archive, "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="Items" sheetId="1" r:id="rId1"/>
</sheets>
</workbook>
""");

AddEntry(archive, "xl/worksheets/sheet1.xml",
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheetData>
<row r="1"><c r="A1" t="s"><v>0</v></c><c r="B1" t="s"><v>1</v></c><c r="C1" t="s"><v>2</v></c></row>
<row r="2"><c r="A2" t="s"><v>3</v></c><c r="B2"><v>35</v></c><c r="C2" t="s"><v>2</v></c></row>
<row r="3"><c r="A3" t="s"><v>4</v></c><c r="B3"><v>25</v></c><c r="C3" t="s"><v>2</v></c></row>
<row r="4"><c r="A4" s="1" t="s"><v>3</v></c><c r="B4"><v>15</v></c></row>
<row r="5"><c r="A5" s="2" t="s"><v>3</v></c><c r="B5"><v>10</v></c></row>
</sheetData>
<tableParts count="1"><tablePart r:id="rId1"/></tableParts>
</worksheet>
""");

AddEntry(archive, "xl/worksheets/_rels/sheet1.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/table" Target="../tables/table1.xml"/>
</Relationships>
""");

AddEntry(archive, "xl/tables/table1.xml",
$"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
id="1" name="Items" displayName="Items" ref="A1:B5" dataDxfId="0">
<tableColumns count="2">
<tableColumn id="1" name="Item"/>
<tableColumn id="2" name="Qty"/>
</tableColumns>
<tableStyleInfo name="Custom" showFirstColumn="{flag}" showLastColumn="0" showRowStripes="{flag}" showColumnStripes="0"/>
</table>
""");

AddEntry(archive, "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"/></font></fonts>
<fills count="4">
<fill><patternFill patternType="none"/></fill>
<fill><patternFill patternType="gray125"/></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFFF0000"/></patternFill></fill>
<fill><patternFill patternType="solid"><fgColor rgb="FFFFFFFF"/></patternFill></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="3">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="0" fontId="0" fillId="2" borderId="0" xfId="0" applyFill="1"/>
<xf numFmtId="0" fontId="0" fillId="3" borderId="0" xfId="0" applyFill="1"/>
</cellXfs>
<dxfs count="4">
<dxf><font><i/></font>{dataDxfFill}</dxf>
<dxf><fill><patternFill><bgColor rgb="FFDDF4F9"/></patternFill></fill></dxf>
<dxf><fill><patternFill><bgColor rgb="FF00B050"/></patternFill></fill></dxf>
<dxf><font><b/></font></dxf>
</dxfs>
<tableStyles count="1" defaultTableStyle="Custom">
<tableStyle name="Custom" pivot="0" count="3">
<tableStyleElement type="wholeTable" dxfId="1"/>
<tableStyleElement type="firstRowStripe" dxfId="2"/>
<tableStyleElement type="firstColumn" dxfId="3"/>
</tableStyle>
</tableStyles>
</styleSheet>
""");

AddEntry(archive, "xl/sharedStrings.xml",
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="5" uniqueCount="5">
<si><t>Item</t></si><si><t>Qty</t></si><si><t>Outside</t></si><si><t>Peonies</t></si><si><t>Tulips</t></si>
</sst>
""");
}

ms.Position = 0;
return ms;
}

private static void AddEntry(ZipArchive archive, string path, string content)
{
var entry = archive.CreateEntry(path);
using var writer = new StreamWriter(entry.Open(), new UTF8Encoding(false));
writer.Write(content);
}
}
6 changes: 5 additions & 1 deletion tests/MiniPdf.Tests/XlsxIssueFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,11 @@ public void BusinessExpensesBudget2_GroupedDrawingUsesPrintScale()
Assert.InRange(firstStripeFill.G, 0.84f, 0.86f);
Assert.InRange(firstStripeFill.B, 0.84f, 0.86f);
Assert.Equal("Benefits", sheet.Rows[9][1].Text);
Assert.Null(sheet.Rows[9][1].FillColor);
// Rows between stripes keep the whole-table fill, as in the Excel reference.
var wholeTableFill = Assert.IsType<PdfColor>(sheet.Rows[9][1].FillColor);
Assert.InRange(wholeTableFill.R, 0.94f, 0.96f);
Assert.InRange(wholeTableFill.G, 0.94f, 0.96f);
Assert.InRange(wholeTableFill.B, 0.94f, 0.96f);

var doc = ExcelToPdfConverter.Convert(issuePath);
var page = doc.Pages[0];
Expand Down
Loading