Question

How can I do to insert the table (see code below) in a specific position of a word file (the location is the text of a paragraph). Then you can set the font and width of the table cells?

Dim table As New Table()
Dim tblBorders As New TableBorders()
tblBorders.TopBorder = New TopBorder()
tblBorders.TopBorder.Val = New EnumValue(Of BorderValues)(BorderValues.[Single])
tblBorders.BottomBorder = New BottomBorder()
tblBorders.BottomBorder.Val = New EnumValue(Of BorderValues)(BorderValues.[Single])
tblBorders.LeftBorder = New LeftBorder()
tblBorders.LeftBorder.Val = New EnumValue(Of BorderValues)(BorderValues.[Single])
tblBorders.RightBorder = New RightBorder()
tblBorders.RightBorder.Val = New EnumValue(Of BorderValues)(BorderValues.[Single])
tblBorders.InsideHorizontalBorder = New InsideHorizontalBorder()
tblBorders.InsideHorizontalBorder.Val = BorderValues.[Single]
tblBorders.InsideVerticalBorder = New InsideVerticalBorder()
tblBorders.InsideVerticalBorder.Val = BorderValues.[Single]
tblPr.Append(tblBorders)
table.Append(tblPr)
trnew = New TableRow()
tc = New TableCell(New Paragraph(New Run(New Text("A"))))
trnew.Append(tc)
tc = New TableCell(New Paragraph(New Run(New Text("B"))))
trnew.Append(tc)
tc = New TableCell(New Paragraph(New Run(New Text("C"))))
Dim tcp As New TableCellProperties()
Dim gridSpan As New GridSpan()
gridSpan.Val = 4
tcp.Append(gridSpan)
tc.Append(tcp)
trnew.Append(tc)
tc = New TableCell(New Paragraph(New Run(New Text("D"))))
trnew.Append(tc)
table.Append(trnew)

thanks!

Was it helpful?

Solution

Access the body of the document, parse down the body and insert the table

C# code below

        //Body is a class in DocumentFormat.OpenXml.Wordprocessing.Body
        // and document part in DocumentFormat.OpenXml.Packaging.MainDocumentPart
        Body body = doc.MainDocumentPart.Document.Body;

        //Traverse the complete document body paragraph by paragraph
        foreach (Paragraph para in body.Descendants<Paragraph>())
        {
           if(para.InnerText.Contains("text the identifies this para")
           {
               para.InserAfterSelf(Table)
           }               
        }

If you don't understand the docx format well, use the openxml productivity tool for open xml version 2.5 http://download.microsoft.com/download/5/5/3/553C731E-9333-40FB-ADE3-E02DC9643B31/OpenXMLSDKToolV25.msi

for version 2.0 http://download.microsoft.com/download/2/7/F/27FF6744-D970-4FFB-90B8-5226B2B82E0A/OpenXMLSDKTool.msi

I havenot worked with the tables in openxml my self, however, it seems to me that you have to create the runs as in tc = New TableCell(New Paragraph(New Run(New Text("A")))) and then add the properties to run, then add the runs into the paragraphs and then into cells- see the link Format Font Inside Table OpenXML C#

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top