使用Open XML的表格单元格边距

问题描述

我想在表级别定义单元格边距,就像这里:OOXML

具有以下代码

var mainDocumentPart = wordDocument.AddMainDocumentPart();

mainDocumentPart.Document = new Document(
    new Body(
        new Paragraph(
            new Run(
                new Text("Create text in body - CreateWordprocessingDocument")))));

// Create an empty table.
Table table = new Table();

// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
    new TableCellSpacing() { Width = "200",Type = TableWidthUnitValues.Dxa },new TableCellMargin(
        new TopMargin() { Width = "50",new StartMargin() { Width = "200",new BottomMargin() { Width = "0",new EndMargin() { Width = "0",Type = TableWidthUnitValues.Dxa })
);

像元间距有效,但像元边距无效。我怎么了?

解决方法

使用 TableCellMarginDefault 代替 TableCellMargin

  • TableCellMarginDefault 影响表。
  • TableCellMargin 影响单个单元格。

您的新代码应如下所示:

var mainDocumentPart = wordDocument.AddMainDocumentPart();

mainDocumentPart.Document = new Document(
    new Body(
        new Paragraph(
            new Run(
                new Text("Create text in body - CreateWordprocessingDocument")))));

// Create an empty table.
Table table = new Table();

// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
    new TableCellSpacing() { Width = "200",Type = TableWidthUnitValues.Dxa },new TableCellMarginDefault(
        new TopMargin() { Width = "50",new StartMargin() { Width = "200",new BottomMargin() { Width = "0",new EndMargin() { Width = "0",Type = TableWidthUnitValues.Dxa })
        );