Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add OpenXmlTableOptions to export sheets as Excel tables
Each exported sheet gets one table over its header and data. Inserting
into an existing workbook and columns placed with gaps are rejected,
since a table can't cover either.
  • Loading branch information
virzak committed Oct 10, 2026
commit 84d82d071dbc454d0c23ce60f8b14f10b404a1b9
20 changes: 20 additions & 0 deletions src/MiniExcel.OpenXml/Constants/ExcelXml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,26 @@ internal static string DrawingRelationship(int sheetIndex)
internal static string DrawingRelationship(int sheetIndex, string drawingFileName)
=> $"""<Relationship Id="rDrawing{sheetIndex}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/{drawingFileName}" />""";

internal static string Table(int id, string name, string reference, bool hasHeaderRow, IReadOnlyList<string> columnNames, OpenXmlTableOptions options)
{
static string Flag(bool value) => value ? "1" : "0";

var sb = new StringBuilder();
sb.Append("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>""");
sb.Append($"""<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="{id}" name="{name}" displayName="{name}" ref="{reference}"{(hasHeaderRow ? "" : " headerRowCount=\"0\"")} totalsRowShown="0">""");
if (hasHeaderRow && options.ShowFilterButton)
sb.Append($"""<autoFilter ref="{reference}" />""");

sb.Append($"""<tableColumns count="{columnNames.Count}">""");
for (var i = 0; i < columnNames.Count; i++)
sb.Append($"""<tableColumn id="{i + 1}" name="{XmlHelper.EncodeXml(columnNames[i])}" />""");
sb.Append("</tableColumns>");

sb.Append($"""<tableStyleInfo name="{XmlHelper.EncodeXml(options.Style)}" showFirstColumn="{Flag(options.ShowFirstColumn)}" showLastColumn="{Flag(options.ShowLastColumn)}" showRowStripes="{Flag(options.ShowRowStripes)}" showColumnStripes="{Flag(options.ShowColumnStripes)}" />""");
sb.Append("</table>");
return sb.ToString();
}

internal static string TableRelationship(int sheetIndex)
=> $"""<Relationship Id="rTable{sheetIndex}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/table" Target="../tables/table{sheetIndex}.xml"/>""";

Expand Down
1 change: 1 addition & 0 deletions src/MiniExcel.OpenXml/Constants/WorksheetXml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,5 @@ internal static string Cell(string cellReference, string? cellType, string style

internal static string Autofilter(string dimensionRef) => $"<x:autoFilter ref=\"{dimensionRef}\" />";
internal static string Drawing(int sheetIndex) => $"<x:drawing r:id=\"rDrawing{sheetIndex}\" />";
internal static string TableParts(int sheetIndex) => $"<x:tableParts count=\"1\"><x:tablePart r:id=\"rTable{sheetIndex}\" /></x:tableParts>";
}
6 changes: 6 additions & 0 deletions src/MiniExcel.OpenXml/OpenXmlConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ public class OpenXmlConfiguration : MiniExcelBaseConfiguration
public bool FillMergedCells { get; set; }
public TableStyles TableStyles { get; set; } = TableStyles.Default;
public bool AutoFilter { get; set; } = true;

/// <summary>
/// When set, each sheet's data is written as an Excel table in this style. The sheet-level <see cref="AutoFilter"/> is then left out.
/// </summary>
public OpenXmlTableOptions? Table { get; set; }

public bool RightToLeft { get; set; } = false;
public int FreezeRowCount { get; set; } = 1;
public int FreezeColumnCount { get; set; } = 0;
Expand Down
47 changes: 47 additions & 0 deletions src/MiniExcel.OpenXml/OpenXmlTableOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace MiniExcelLib.OpenXml;

/// <summary>
/// Exports each sheet's data as an Excel table. Set it on <see cref="OpenXmlConfiguration.Table"/>.
/// </summary>
/// <remarks>
/// The table covers the header row and the data, so columns must be adjacent. Combine it with
/// <see cref="TableStyles.None"/> to let the table style alone format the cells.
/// </remarks>
public class OpenXmlTableOptions
{
/// <summary>
/// The table name. The first sheet's table gets this name and later sheets append their sheet number.
/// Defaults to Table1, Table2 and so on.
/// </summary>
public string? Name { get; set; }

/// <summary>
/// A built-in table style such as TableStyleMedium2 or TableStyleLight9.
/// </summary>
public string Style { get; set; } = "TableStyleMedium2";

/// <summary>
/// Shows filter buttons in the header row.
/// </summary>
public bool ShowFilterButton { get; set; } = true;

/// <summary>
/// Shades alternate rows.
/// </summary>
public bool ShowRowStripes { get; set; } = true;

/// <summary>
/// Shades alternate columns.
/// </summary>
public bool ShowColumnStripes { get; set; }

/// <summary>
/// Highlights the first column.
/// </summary>
public bool ShowFirstColumn { get; set; }

/// <summary>
/// Highlights the last column.
/// </summary>
public bool ShowLastColumn { get; set; }
}
38 changes: 37 additions & 1 deletion src/MiniExcel.OpenXml/Writer/OpenXmlWriter.XmlGeneration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,39 @@ private string GetDrawingXml(int sheetIndex)
return drawing.ToString();
}

private static readonly Regex TableNameRegex = new(@"^[A-Za-z_\][A-Za-z0-9_.]*$");

private string? GetTableXml(OpenXmlTableOptions options, List<MiniExcelColumnMapping?> mappings, int maxRowIndex, int maxColumnIndex)
{
// Null mappings are gaps between columns placed by index, which would leave a table column without a header
if (mappings.Any(m => m is null))
throw new NotSupportedException("A table needs adjacent columns, so it can't be used with column indexes that leave gaps");

if (maxColumnIndex == 0 || (!_printHeader && maxRowIndex == 0))
return null;

List<string> columnNames = _printHeader
? [.. mappings.Where(m => !m!.ExcelIgnoreColumn).Select(m => m!.ExcelColumnName ?? "")]
: [.. Enumerable.Range(1, maxColumnIndex).Select(i => $"Column{i}")];

if (columnNames.Any(string.IsNullOrEmpty))
throw new InvalidOperationException("Table column names can't be empty");
if (columnNames.Distinct(StringComparer.OrdinalIgnoreCase).Count() != columnNames.Count)
throw new InvalidOperationException("Table column names must be unique");

var name = options.Name is null ? $"Table{_currentSheetIndex}"
: _currentSheetIndex == 1 ? options.Name
: $"{options.Name}{_currentSheetIndex}";
if (!TableNameRegex.IsMatch(name))
throw new ArgumentException($"'{name}' is not a valid table name");

// A table needs at least one data row, so a header without data takes in the empty row below it
var lastRow = _printHeader ? Math.Max(maxRowIndex, 2) : maxRowIndex;
var reference = $"A1:{CellReferenceConverter.GetCellFromCoordinates(maxColumnIndex, lastRow)}";

return ExcelXml.Table(_currentSheetIndex, name, reference, _printHeader, columnNames, options);
}

private (string WorkbookContents, string WorkbookRelsContents, Dictionary<int, string> SheetRelsContents) GenerateWorkbookItems()
{
var workbookContents = new StringBuilder();
Expand All @@ -419,7 +452,10 @@ private string GetDrawingXml(int sheetIndex)
workbookRelsContents.AppendLine(ExcelXml.WorksheetRelationship(sheetDto));

//TODO: support multiple drawing
sheetsRelsDict.Add(sheetDto.SheetIdx, ExcelXml.DrawingRelationship(sheetId));
var sheetRels = ExcelXml.DrawingRelationship(sheetId);
if (_tables.ContainsKey(sheetDto.SheetIdx))
sheetRels += ExcelXml.TableRelationship(sheetDto.SheetIdx);
sheetsRelsDict.Add(sheetDto.SheetIdx, sheetRels);
}

return (workbookContents.ToString(), workbookRelsContents.ToString(), sheetsRelsDict);
Expand Down
25 changes: 24 additions & 1 deletion src/MiniExcel.OpenXml/Writer/OpenXmlWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ internal sealed partial class OpenXmlWriter : IMiniExcelWriter
private readonly OpenXmlConfiguration _configuration;
private readonly List<SheetDto> _sheets = [];
private readonly List<FileDto> _files = [];

// Table parts by sheet index, written once all sheets are done
private readonly Dictionary<int, string> _tables = [];

private readonly string _sheetName;
private readonly bool _printHeader;
Expand Down Expand Up @@ -86,6 +89,7 @@ public async Task<int[]> SaveAsAsync(IProgress<int>? progress = null, Cancellati
await GenerateSharedStringsAsync(cancellationToken).ConfigureAwait(false);
await GenerateDrawingRelsAsync(cancellationToken).ConfigureAwait(false);
await GenerateDrawingsAsync(cancellationToken).ConfigureAwait(false);
await GenerateTablesAsync(cancellationToken).ConfigureAwait(false);
await GenerateWorkbookAsync(false, cancellationToken).ConfigureAwait(false);
await GenerateContentTypesAsync(cancellationToken).ConfigureAwait(false);

Expand All @@ -97,6 +101,8 @@ public async Task<int> InsertAsync(bool overwriteSheet = false, IProgress<int>?
{
if (!_configuration.FastMode)
throw new InvalidOperationException("Insert requires fast mode to be enabled");
if (_configuration.Table is not null)
throw new NotSupportedException("Tables can't be added when inserting a sheet into an existing workbook");

#if NET10_0_OR_GREATER
await using var disposableArchive = _archive.ConfigureAwait(false);
Expand Down Expand Up @@ -331,12 +337,19 @@ private async Task<int> WriteValuesAsync(MiniExcelStreamWriter writer, object va

await writer.WriteAsync(WorksheetXml.EndSheetData, cancellationToken).ConfigureAwait(false);

if (_configuration.AutoFilter)
// A sheet can't have its own autofilter on top of a table's
var table = _configuration.Table is { } tableOptions ? GetTableXml(tableOptions, mappings, maxRowIndex, maxColumnIndex) : null;
if (_configuration.AutoFilter && _configuration.Table is null)
{
await writer.WriteAsync(WorksheetXml.Autofilter(GetDimensionRef(maxRowIndex, maxColumnIndex)), cancellationToken).ConfigureAwait(false);
}

await writer.WriteAsync(WorksheetXml.Drawing(_currentSheetIndex), cancellationToken).ConfigureAwait(false);
if (table is not null)
{
_tables[_currentSheetIndex] = table;
await writer.WriteAsync(WorksheetXml.TableParts(_currentSheetIndex), cancellationToken).ConfigureAwait(false);
}
await writer.WriteAsync(WorksheetXml.EndWorksheet, cancellationToken).ConfigureAwait(false);

if (_archive.Mode == ZipArchiveMode.Update && dimensionPlaceholderPostition != 0)
Expand Down Expand Up @@ -564,6 +577,16 @@ await CreateZipEntryAsync(
cancellationToken).ConfigureAwait(false);
}

[CreateSyncVersion]
private async Task GenerateTablesAsync(CancellationToken cancellationToken)
{
foreach (var (sheetIndex, table) in _tables)
{
cancellationToken.ThrowIfCancellationRequested();
await CreateZipEntryAsync(ExcelFileNames.Table(sheetIndex), ExcelContentTypes.Table, table, cancellationToken).ConfigureAwait(false);
}
}

[CreateSyncVersion]
private async Task GenerateWorkbookAsync(bool removeOriginalEntry = false, CancellationToken cancellationToken = default)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
using ClosedXML.Excel;

namespace MiniExcelLib.OpenXml.Tests.Tables;

public class MiniExcelOpenXmlTableExportAsyncTests
{
private readonly OpenXmlExporter _exporter = MiniExcelV2.Exporters.GetOpenXmlExporter();
private readonly OpenXmlImporter _importer = MiniExcelV2.Importers.GetOpenXmlImporter();

private class Weld
{
public int Id { get; set; }
public string? Name { get; set; }
public double Depth { get; set; }
}

private class IndexedWeld
{
[MiniExcelColumnIndex(0)]
public int Id { get; set; }

[MiniExcelColumnIndex(2)]
public double Depth { get; set; }
}

private static readonly Weld[] Welds =
[
new() { Id = 1, Name = "first", Depth = 0.1 },
new() { Id = 2, Name = "second", Depth = 0.2 }
];

private async Task<MemoryStream> ExportAsync(object value, OpenXmlConfiguration configuration, bool printHeader = true)
{
var stream = new MemoryStream();
await _exporter.ExportAsync(stream, value, printHeader, configuration: configuration);
stream.Position = 0;
return stream;
}

[Fact]
public async Task DataIsWrittenAsATableInTheChosenStyleAsync()
{
var configuration = new OpenXmlConfiguration
{
TableStyles = TableStyles.None,
Table = new OpenXmlTableOptions { Name = "Welds", Style = "TableStyleMedium15", ShowFilterButton = false }
};

using var stream = await ExportAsync(Welds, configuration);
using var workbook = new XLWorkbook(stream);
var table = workbook.Worksheet(1).Tables.Single();

Assert.Equal("Welds", table.Name);
Assert.Equal("A1:C3", table.RangeAddress.ToString());
Assert.Equal(["Id", "Name", "Depth"], table.Fields.Select(f => f.Name));
Assert.Equal(XLTableTheme.TableStyleMedium15, table.Theme);
Assert.False(table.ShowAutoFilter);
Assert.True(table.ShowRowStripes);
Assert.Null(workbook.Worksheet(1).AutoFilter.Range);

stream.Position = 0;
var rows = await _importer.QueryTableAsync(stream, tableName: "Welds").ToListAsync();
Assert.Equal(2, rows.Count);
Assert.Equal("second", (string)rows[1].Name);
}

[Fact]
public async Task EachSheetGetsItsOwnTableAsync()
{
var sheets = new Dictionary<string, object> { ["First"] = Welds, ["Second"] = Welds.Take(1) };

using var stream = await ExportAsync(sheets, new OpenXmlConfiguration { Table = new OpenXmlTableOptions() });
using var workbook = new XLWorkbook(stream);

Assert.Equal("Table1", workbook.Worksheet("First").Tables.Single().Name);
Assert.Equal("A1:C3", workbook.Worksheet("First").Tables.Single().RangeAddress.ToString());
Assert.Equal("Table2", workbook.Worksheet("Second").Tables.Single().Name);
Assert.Equal("A1:C2", workbook.Worksheet("Second").Tables.Single().RangeAddress.ToString());
Assert.True(workbook.Worksheet("First").Tables.Single().ShowAutoFilter);
}

[Fact]
public async Task HeaderWithoutDataStillMakesATableAsync()
{
using var stream = await ExportAsync(Array.Empty<Weld>(), new OpenXmlConfiguration { Table = new OpenXmlTableOptions() });
using var workbook = new XLWorkbook(stream);

Assert.Equal("A1:C2", workbook.Worksheet(1).Tables.Single().RangeAddress.ToString());
}

[Fact]
public async Task TableWithoutHeaderRowAsync()
{
using var stream = await ExportAsync(Welds, new OpenXmlConfiguration { Table = new OpenXmlTableOptions() }, printHeader: false);
using var workbook = new XLWorkbook(stream);
var table = workbook.Worksheet(1).Tables.Single();

Assert.False(table.ShowHeaderRow);
Assert.Equal("A1:C2", table.RangeAddress.ToString());
}

[Fact]
public async Task ColumnGapsAreRejectedAsync()
{
IndexedWeld[] rows = [new() { Id = 1, Depth = 0.1 }];

await Assert.ThrowsAsync<NotSupportedException>(() => ExportAsync(rows, new OpenXmlConfiguration { Table = new OpenXmlTableOptions() }));
}

[Fact]
public async Task InvalidTableNameIsRejectedAsync()
{
var configuration = new OpenXmlConfiguration { Table = new OpenXmlTableOptions { Name = "My Welds" } };

await Assert.ThrowsAsync<ArgumentException>(() => ExportAsync(Welds, configuration));
}

[Fact]
public async Task InsertingASheetWithATableIsRejectedAsync()
{
using var stream = await ExportAsync(Welds, new OpenXmlConfiguration());
var configuration = new OpenXmlConfiguration { FastMode = true, Table = new OpenXmlTableOptions() };

await Assert.ThrowsAsync<NotSupportedException>(() => _exporter.InsertSheetAsync(stream, Welds, "Second", configuration: configuration));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using ClosedXML.Excel;

namespace MiniExcelLib.OpenXml.Tests.Tables;

public class MiniExcelOpenXmlTableExportTests
{
private readonly OpenXmlExporter _exporter = MiniExcelV2.Exporters.GetOpenXmlExporter();

[Fact]
public void DataIsWrittenAsATable()
{
var rows = new[] { new { Id = 1, Name = "first" }, new { Id = 2, Name = "second" } };
var configuration = new OpenXmlConfiguration { Table = new OpenXmlTableOptions { Style = "TableStyleLight9" } };

var stream = new MemoryStream();
_exporter.Export(stream, rows, configuration: configuration);
stream.Position = 0;

using var workbook = new XLWorkbook(stream);
var table = workbook.Worksheet(1).Tables.Single();
Assert.Equal("Table1", table.Name);
Assert.Equal("A1:B3", table.RangeAddress.ToString());
Assert.Equal(XLTableTheme.TableStyleLight9, table.Theme);
}
}
Loading