Whenver I try and nest tables in a new Wordprocessing Document, the file won't open. Here is a basic example of what I'm trying to accomplish
Using wordDoc As WordprocessingDocument = WordprocessingDocument.Create("C:\Integration\Nested.docx", DocumentFormat.OpenXml.WordprocessingDocumentType.Document) '---- Create Main Document Dim mainDocument As MainDocumentPart = wordDoc.AddMainDocumentPart() mainDocument.Document = New DocumentFormat.OpenXml.Wordprocessing.Document() Dim body As New DocumentFormat.OpenXml.Wordprocessing.Body() '--- Create Parent Table Dim tbl1 As New DocumentFormat.OpenXml.Wordprocessing.Table Dim row1 As New DocumentFormat.OpenXml.Wordprocessing.TableRow Dim col1 As New DocumentFormat.OpenXml.Wordprocessing.TableCell(New DocumentFormat.OpenXml.Wordprocessing.Paragraph)
'--- Create Nested Table Dim tbl2 As New DocumentFormat.OpenXml.Wordprocessing.Table Dim row2 As New DocumentFormat.OpenXml.Wordprocessing.TableRow Dim col2 As New DocumentFormat.OpenXml.Wordprocessing.TableCell(New DocumentFormat.OpenXml.Wordprocessing.Paragraph(New DocumentFormat.OpenXml.Wordprocessing.Run(New DocumentFormat.OpenXml.Wordprocessing.Text("Test"))))
'--- Add Cell and Row to Nested Table row2.Append(col2) tbl2.Append(row2) '--- Add Nested Table to Parent Cell col1.Append(tbl2) '--- Add Cell and Row to Parent Table row1.Append(col1) tbl1.Append(row1) '--- Add Parent Table to Body body.Append(tbl1) '--- Add Body to Document and Save mainDocument.Document.Append(body) mainDocument.Document.Save()End Using
I'm not sure, but I would guess that the main document part isn't enough. Try to figure out which parts need also to be created in order to create a valid document. Or this happens only when you add a second, nested table inside a cell of the first table?
It only happens when I add a second nested table inside a cell of the first table. I finally found a solution after searching and a lot of trial and error. I don't know why this works, but If you append a paragrah after you append the nested table the document opens successfully.
As I know, you cannot have an empty table cell without a paragraph. Still, I would say that having another table inside a parent cell as its only child element wouldn't pose a problem, ... but as you found out it does! I gues it is the same as a blank document - even a blank document starts with a paragraph, otherwise there would be no starting position for the cursor.
If you are doing data driven document generation you might also want to take a look at Docentric toolkit. It is also able to render hierarchical data in the form of n-level nested tables.