简体   繁体   中英

How to set table caption with OpenXML?

I want to set caption to my table:

var caption = new TableCaption();
caption.Val = "Test";
table.Append(caption);

But nothing happens. Whats wrong here?

UPADATE

                foreach (var tabl in mainPart.Document.Body.Descendants<Table>())
                {
                    foreach (var trow in tabl.Elements<TableRow>())
                    {
                        foreach (var tcell in trow.Elements<TableCell>())
                        {
                            foreach (var para in tcell.Elements<Paragraph>())
                            {
                                foreach (var run in para.Elements<Run>())
                                {
                                    foreach (var text in run.Elements<Text>())
                                    {
                                        if (
                                            text.Text ==
                                                "my caption")
                                        {
                                            para.RemoveAllChildren();
                                            para.Remove();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

In your code, I guess the table is a DocumentFormat.OpenXml.Wordprocessing.Table . This is not a valid parent for this element. The TableCaption should be added to a TableProperties element <w:tblPr> .

Table table = new Table();
TableProperties tableProperties = new TableProperties(
                  new TableCaption() { Val = "Test" }
                );
table.AppendChild<TableProperties>(tableProperties);

Then note the <w:tblCaption> element was added in the 2008 version of ECMA-376, so Word 2007 does not support this. The TableCaption class is only available since Office2010.

To add/see this caption in word:

Right-Click on the table->Properties->Text/Replacement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM