Word OpenXML 删除 table 内的填充

Word OpenXML remove padding inside table

我正在使用 word open XML。

rowCopy.Descendants<TableCell>().ElementAt(0).Append(new Paragraph(new Run(new Text(dr["NAME"].ToString()))));

关于代码正在将名称写入 table 中的单元格。但它正在单元格内创建顶部和底部填充。我怎样才能删除它。是因为新的段落吗?我是 word open XML.

的新手

[![在此处输入图片描述][2]][2]

如果您现有的 Docx 文件中有一个空的 table,您可能会发现每个 Cell 中都有一个空的 Paragraph。通过使用 Append,您将在空的 Paragraph 之后添加新的 Paragraph,这会导致单元格顶部的 space 看起来像填充。

鉴于您只需要 Cell 中的新文本,您可以在添加新的 Paragraph[=38= 之前删除任何现有的 Paragraph 元素 ] 通过在 Cell 上调用 RemoveAllChildren(如果您确信在 Table 上不需要任何 Table):

TableCell cell = body.Descendants<TableCell>().ElementAt(0);
cell.RemoveAllChildren<Paragraph>();
cell.Append(new Paragraph(new Run(new Text(dr["NAME"].ToString()))));

如果这不是问题,那么您可以通过编辑 TableCellMargin 来控制填充。像下面这样的东西应该可以工作:

if (cell.TableCellProperties != null && cell.TableCellProperties.TableCellMargin != null)
{
    cell.TableCellProperties.TableCellMargin.BottomMargin = new BottomMargin() { Width = "0" };
    cell.TableCellProperties.TableCellMargin.TopMargin = new TopMargin() { Width = "0" };
}

编辑

完整的代码清单如下所示:

static void AddDataToTable(string filename)
{
    using (WordprocessingDocument wordDoc =
            WordprocessingDocument.Open(filename, true))
    {
        var body = wordDoc.MainDocumentPart.Document.Body;
        var paras = body.Elements<TableCell>();

        TableCell cell = body.Descendants<TableCell>().ElementAt(0);
        cell.RemoveAllChildren<Paragraph>();
        cell.Append(new Paragraph(new Run(new Text(dr["NAME"].ToString()))));

        if (cell.TableCellProperties != null && cell.TableCellProperties.TableCellMargin != null)
        {
            cell.TableCellProperties.TableCellMargin.BottomMargin = new BottomMargin() { Width = "0" };
            cell.TableCellProperties.TableCellMargin.TopMargin = new TopMargin() { Width = "0" };
        }

        wordDoc.Close(); // close the template file
    }
}