Skip to main content
 首页 » 编程设计

c#之使用c#以编程方式设置word文档表格单元格边距

2024年02月06日14zhenyulu

因为我们可以使用此步骤更改 MS WORD 中的默认表格单元格边距

Click the table. 
On the Table menu, click Table Properties, and then click the Table tab. 
Click Options. 
Under Default cell margins, enter the new values you want. 

确切地说,我想问的是如何以编程方式执行此操作,我已经尝试了 top 和 bottom padding 属性,但它没有用,而且我还尝试了 spacing 但我没有也可以使用 Microsoft.Interop.Word 库设置默认单元格边距,非常感谢

附言: 我正在使用 Microsoft.Interop.Word 在页眉和页脚中添加表格,一切都完美无缺:/

请您参考如下方法:

有Table padding,也有Cell padding。我猜 Table padding 包含应用于添加到表中的新单元格的默认值。可能使用单元格填充来更改现有单元格。例如

    Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); 
    Documents docs = app.Documents; 
    Document doc = docs.Open("C:\\temp\\Test2.docx", ReadOnly:true); 
    Table t = doc.Tables[1]; 
    double b1 = t.BottomPadding; 
    double t1 = t.TopPadding; 
    double r1 = t.RightPadding; 
    double l1 = t.LeftPadding; 
 
    Range r = t.Range; 
    Cells cells = r.Cells; 
    for (int i = 1; i <= cells.Count; i++) { 
        Cell cell = cells[i]; 
        double b2 = cell.BottomPadding; 
        double t2 = cell.TopPadding; 
        double r2 = cell.RightPadding; 
        double l2 = cell.LeftPadding; 
 
        // e.g. Here is the edit: 
        cell.TopPadding = 21.6f; 
        cell.BottomPadding = 28.8f; 
 
        Range r2b = cell.Range; 
        String txt = r2b.Text; 
        Marshal.ReleaseComObject(cell); 
        Marshal.ReleaseComObject(r2b); 
    } 
 
    doc.Close(false); 
    app.Quit(false); 
    Marshal.ReleaseComObject(cells); 
    Marshal.ReleaseComObject(r); 
    Marshal.ReleaseComObject(t); 
    Marshal.ReleaseComObject(doc); 
    Marshal.ReleaseComObject(docs); 
    Marshal.ReleaseComObject(app);