我正在尝试在*.docx-documents的表格单元格中对齐文本。
一切正常,直到我将tablecellproperty附加到tablecell本身。

TableCell tc = new TableCell();

TableCellProperties tcpVA = new TableCellProperties();
TableCellVerticalAlignment tcVA= new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center };
tcpVA.Append(tcVA);

tc.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = columnwidths[i] }), tcpVA);


附加cellwidth,颜色等效果很好,但仅TableCellVerticalAlignment不起作用。

TableCellProperty的值已设置:

Val = "center"


但是在将TableCellProperties附加到tablecell之后,将verticalalignment的属性添加:

TableCellVerticalAlignment = null

最佳答案

您要向TableCellProperties添加两个TableCell,一个用于垂直对齐,另一个用于像元宽度。该模式仅允许一个TableCellProperties

TableCellVerticalAlignmentTableCellWidth都应附加到相同的TableCellProperties,然后仅应将TableCellProperties添加到单元格中。

下面的方法是一个示例,该示例将创建一个带有一个表的文档,该表具有一个单元格,该单元格同时设置了width和alignment属性以及文本“ Hello World!”。在里面。

public static void CreateWordDoc(string filename)
{
    using (var wordDocument = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document))
    {
        // Add a main document part.
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

        // Create the document structure
        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());

        //add a table, row and column
        Table table = body.AppendChild(new Table());
        TableRow row = table.AppendChild(new TableRow());
        TableCell tc = row.AppendChild(new TableCell());

        //create the cell properties
        TableCellProperties tcp = new TableCellProperties();
        //create the vertial alignment properties
        TableCellVerticalAlignment tcVA = new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center };
        //create the cell width
        TableCellWidth tcW = new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "100" };
        //append the vertical alignment and cell width objects to the TableCellProperties
        tcp.Append(tcW);
        tcp.Append(tcVA);

        //append ONE TableCellProperties object to the cell
        tc.Append(tcp);

        //add some text to the cell to test.
        Paragraph para = tc.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text("Hello World!"));

        mainPart.Document.Save();
    }
}

09-07 05:19