DocX
DocX copied to clipboard
How to add nested table inside newly generated word .docx file ?
Hi,
I started working on to implement xceed.docx library to generate docx file.
Today I tried to add nested table inside doc file but I am not able to achieve that.
Do you have any idea how to do that ?
Here is the sample code:
` var firstTable = document.AddTable(1, 2);
firstTable.SetWidthsPercentage(new[] { 60f, 40f });
firstTable.Design = TableDesign.TableGrid;
document.InsertTable(firstTable);
List<Cell> lstCell = firstTable.Rows[0].Cells;
var secondTable = document.AddTable(1, 3);
lstCell[0].Paragraphs[0].InsertTable(secondTable);
document.InsertTable(secondTable); `
Please let me know.
Thanks, Dipak Patel
Hello, Try with something like this: ` var document = DocX.Create("test.docx");
var firstTable = document.AddTable( 1, 2 );
firstTable.SetWidthsPercentage( new[] { 60f, 40f } );
firstTable.Design = TableDesign.TableGrid;
var secondTable = document.AddTable( 1, 3 );
firstTable.Rows[ 0 ].Cells[ 0 ].InsertTable( secondTable );
//firstTable.Rows[ 0 ].Cells[ 0 ].Paragraphs[0].InsertTableAfterSelf( secondTable );
document.InsertTable( firstTable );
document.Save();`
We will investigate why InsertTableAfterSelf doesn't work.
Thanks for the reply Boucher.
I tried with the code that provided by you but it gives an alert message when opening up the word file.
Screenshot 1:

Screenshot 2: When pressing yes

I want this type of table layout with nested table: Below is the screenshot with Main table of two columns with nested table as highlighted in red color.

Hi,
Here is the complete sample I used to create your expected table. Please note that creating a table automatically creates an empty paragraph in each cell which you can remove with ".RemoveParagraphAt( 0 ) ".
`var document = DocX.Create("test.docx");
var mainTable = document.AddTable( 1, 2 );
mainTable.SetWidthsPercentage( new[] { 60f, 40f } );
mainTable.SetTableCellMargin( TableCellMarginType.left, 0f );
var subTable = document.AddTable( 5, 2 );
subTable.SetWidthsPercentage( new[] { 20f, 80f } );
subTable.Rows[ 0 ].Cells[ 0 ].FillColor = Color.LightGray;
subTable.Rows[ 0 ].Cells[ 0 ].RemoveParagraphAt( 0 );
subTable.Rows[ 0 ].Cells[ 0 ].InsertParagraph( "Icon" );
subTable.Rows[ 0 ].Cells[ 1 ].RemoveParagraphAt( 0 );
subTable.Rows[ 0 ].Cells[ 1 ].InsertParagraph( "Some text\nSome text" );
for( int i = 1; i < 5; ++i )
{
subTable.Rows[ i ].MergeCells( 0, 1 );
subTable.Rows[ i ].Cells[ 0 ].RemoveParagraphAt( 0 );
subTable.Rows[i].Cells[0].InsertParagraph( "Some text" );
}
mainTable.Rows[ 0 ].Cells[ 1 ].FillColor = Color.Pink;
mainTable.Rows[ 0 ].Cells[ 1 ].InsertParagraph("Image");
mainTable.Rows[ 0 ].Cells[ 0 ].RemoveParagraphAt( 0 );
mainTable.Rows[ 0 ].Cells[ 0 ].InsertTable( subTable );
//firstTable.Rows[ 0 ].Cells[ 0 ].Paragraphs[0].InsertTableAfterSelf( secondTable );
document.InsertTable( mainTable );
document.Save();`