Skip to content
This repository was archived by the owner on Aug 26, 2022. It is now read-only.

Add the possibility to enable the AutoFilter feature #35

Merged
merged 1 commit into from
Apr 27, 2022
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
2 changes: 1 addition & 1 deletion src/Simplexcel.TestApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ static void Main()
populatedSheet.Populate(EnumeratePopulateTestData(), cacheTypeColumns: true);
wb.Add(populatedSheet);

var frozenTopRowSheet = new Worksheet("Frozen Top Row");
var frozenTopRowSheet = new Worksheet("Frozen Top Row") { AutoFilter = true };
frozenTopRowSheet.Cells[0, 0] = "Header 1";
frozenTopRowSheet.Cells[0, 1] = "Header 2";
frozenTopRowSheet.Cells[0, 2] = "Header 3";
Expand Down
8 changes: 8 additions & 0 deletions src/Simplexcel/Worksheet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ public ColumnWidthCollection ColumnWidths
/// </summary>
public LargeNumberHandlingMode LargeNumberHandlingMode { get; set; }

/// <summary>
/// Whether to enable the AutoFilter feature on the first non-empty row.
/// <para/>
/// Defaults to <see langword="false"/>.
/// </summary>
/// <remarks>See <a href="https://support.microsoft.com/en-us/office/use-autofilter-to-filter-your-data-7d87d63e-ebd0-424b-8106-e2ab61133d92">Use AutoFilter to filter your data</a></remarks>
public bool AutoFilter { get; set; }

/// <summary>
/// Get the cell with the given cell reference, e.g. Get the cell "A1". May return NULL.
/// </summary>
Expand Down
11 changes: 11 additions & 0 deletions src/Simplexcel/XlsxInternal/XlsxWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -473,8 +473,10 @@ private static Relationship CreateSheetFile(Worksheet sheet, int sheetIndex, Rel
}

var sheetData = new XElement(Namespaces.workbook + "sheetData");
XlsxRow firstRow = null;
foreach (var row in rows.OrderBy(rk => rk.Key))
{
firstRow ??= row.Value;
var re = new XElement(Namespaces.workbook + "row", new XAttribute("r", row.Value.RowIndex));
foreach (var cell in row.Value.Cells)
{
Expand All @@ -498,6 +500,15 @@ private static Relationship CreateSheetFile(Worksheet sheet, int sheetIndex, Rel
}
doc.Root.Add(sheetData);

var firstRowCells = firstRow?.Cells;
if (sheet.AutoFilter && firstRowCells?.Count > 0)
{
var firstRef = firstRowCells.First().Reference;
var lastRef = firstRowCells.Last().Reference;
var autoFilter = new XElement(Namespaces.workbook + "autoFilter", new XAttribute("ref", $"{firstRef}:{lastRef}"));
doc.Root.Add(autoFilter);
}

sheetRels = null;
var hyperlinks = sheet.Cells.Where(c => c.Value != null && !string.IsNullOrEmpty(c.Value.Hyperlink)).ToList();
if (hyperlinks.Count > 0)
Expand Down