diff --git a/DocxTemplater.Test/DocxTemplateTest.cs b/DocxTemplater.Test/DocxTemplateTest.cs
index a028a08..6c8a6d6 100644
--- a/DocxTemplater.Test/DocxTemplateTest.cs
+++ b/DocxTemplater.Test/DocxTemplateTest.cs
@@ -43,6 +43,24 @@ public void DynamicTable()
Assert.That(rows[4].InnerText, Is.EqualTo("Value7Value8Value9"));
}
+ [Test]
+ public void EmptyDynamicTable()
+ {
+ using var fileStream = File.OpenRead("Resources/DynamicTable.docx");
+ var docTemplate = new DocxTemplate(fileStream);
+ var tableModel = new DynamicTable();
+ docTemplate.BindModel("ds", tableModel);
+ var result = docTemplate.Process();
+ docTemplate.Validate();
+ result.Position = 0;
+ result.SaveAsFileAndOpenInWord();
+ result.Position = 0;
+ var document = WordprocessingDocument.Open(result, false);
+ var body = document.MainDocumentPart.Document.Body;
+ var table = body.Descendants
().FirstOrDefault();
+ Assert.That(table, Is.Null);
+ }
+
///
/// Dynamic tables are only required if the number of columns is not known at design time.
/// otherwise a simple table bound to a collection of objects is sufficient.
@@ -321,6 +339,7 @@ public void CollectionSeparatorTest()
Assert.That(body.InnerText, Is.EqualTo("Item1,Item2,Item3"));
}
+
[Test]
public void ConditionsWithAndWithoutPrefix()
{
diff --git a/DocxTemplater/Blocks/DynamicTableBlock.cs b/DocxTemplater/Blocks/DynamicTableBlock.cs
index e3f0c16..3fbd697 100644
--- a/DocxTemplater/Blocks/DynamicTableBlock.cs
+++ b/DocxTemplater/Blocks/DynamicTableBlock.cs
@@ -21,6 +21,10 @@ public override void Expand(ModelLookup models, OpenXmlElement parentNode)
var model = models.GetValue(m_tablenName);
if (model is IDynamicTable dynamicTable)
{
+ if (!dynamicTable.Headers.Any())
+ {
+ return;
+ }
var headersName = $"{m_tablenName}.{nameof(IDynamicTable.Headers)}";
var columnsName = $"{m_tablenName}.{nameof(IDynamicTable.Rows)}";
@@ -74,7 +78,7 @@ public override void Expand(ModelLookup models, OpenXmlElement parentNode)
dataCell.Remove();
// ensure all rows have the same number of cells
- var maxCells = dynamicTable.Rows.Max(r => r.Count());
+ var maxCells = dynamicTable.Rows.DefaultIfEmpty().Max(r => r?.Count() ?? 0);
foreach (var row in table.Elements())
{
var cells = row.Elements().ToList();