The Table layout that I am trying to achieve is displayed in Table 2 within the attached document. The code I am using is listed below and the result of this code is displayed in Table 1 within the attached document. Note I am not using the DocumentBuilder option to insert tables instead I am inserting tables directly into the Document Object Model. I have tried various solutions found in the Forms but none have worked. Please advise.
public void Process()
{
…
…
var table = SetTableHeader();
SetSubHeader(table,SubHeader);
InsertData(table,MainData);
_document.Save("C:\temp\test.docx");
}
private Table SetTableHeader()
{
var table = new Table(_document);
var row = new Row(_document);
row.RowFormat.AllowBreakAcrossPages = false;
row.RowFormat.HeadingFormat = true;
var cell = new Cell(_document);
var cellparagraph = new Paragraph(_document);
cell.AppendChild(cellparagraph);
cell.FirstParagraph.AppendChild(new Run(_document, "Header Table Row"));
row.AppendChild(cell);
table.AppendChild(row);
_document.FirstSection.Body.AppendChild(table);
return table;
}
private void SetSubHeader(Table table, SubHeader subHeader)
{
Row row = new Row(_document);
row.RowFormat.AllowBreakAcrossPages = false;
var cell = new Cell(_document);
var cellparagraph = new Paragraph(_document);
cell.AppendChild(cellparagraph);
cell.FirstParagraph.AppendChild(new Run(_document, SubHeader.Description));
row.AppendChild(cell);
foreach (var col in subHeader.Columns)
{
cell = new Cell(_document);
cellparagraph = new Paragraph(_document);
cellparagraph.AppendChild(new Run(_document, col.Description));
cell.AppendChild(cellparagraph);
row.AppendChild(cell);
}
table.Rows.Add(row);
}
private void InsertData(Table tabel, Data mainData)
{
foreach (var data in mainData.Data)
{
var row = new Row(_document);
var cell = new Cell(_document);
var cellparagraph = new Paragraph(_document);
cell.AppendChild(cellparagraph);
cell.FirstParagraph.AppendChild(new Run(_document, data.Description));
row.AppendChild(cell);
foreach (var dataDetail in data.Details)
{
cell = new Cell(_document);
cellparagraph = new Paragraph(_document);
cell.AppendChild(cellparagraph);
cell.FirstParagraph.AppendChild(new Run(_document, dataDetail.Description));
row.AppendChild(cell);
}
tabel.Rows.Add(row);
}
}