2013-05-29 34 views
2

以下代碼插入一個表到Word文檔:帶有邊界的字表

using Word = Microsoft.Office.Interop.Word; 
... 
object oMissing = System.Reflection.Missing.Value; 
object oEndOfDoc = "\\endofdoc"; 
Word._Application oWord; 
Word._Document oDoc; 
oWord = new Word.Application(); 
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

Word.Table oTable; 
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); 
oTable.Range.ParagraphFormat.SpaceAfter = 6; 
int r, c; 
string strText; 
for (r = 1; r <= 3; r++) 
    for (c = 1; c <= 5; c++) 
    { 
     strText = "r" + r + "c" + c; 
     oTable.Cell(r, c).Range.Text = strText; 
    } 

此代碼是從所述製品:http://support.microsoft.com/Default.aspx?scid=kb;en-us;316384&spid=2530&sid=47

結果是:

 
r1c1 r1c2 r1c3 r1c4 r1c5 
r2c1 r2c2 r2c3 r2c4 r2c5 
r3c1 r3c2 r3c3 r3c4 r3c5 

得到的表沒有按沒有邊界。如何更改此代碼以獲取帶有邊框的表格,如「插入表格」Word命令?

回答

6

試試這個變種:

oTable.Cell(r, c).Range.Borders[WdBorderType.wdBorderLeft].LineStyle = WdLineStyle.wdLineStyleSingle; 
oTable.Cell(r, c).Range.Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.wdLineStyleSingle; 
oTable.Cell(r, c).Range.Borders[WdBorderType.wdBorderTop].LineStyle = WdLineStyle.wdLineStyleSingle; 
oTable.Cell(r, c).Range.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleSingle; 

投放週期。你

也可以設置線的寬度和顏色:

oTable.Cell(r, c).Range.Borders[WdBorderType.wdBorderBottom].LineWidth = WdLineWidth.wdLineWidth050pt; 
oTable.Cell(r, c).Range.Borders[WdBorderType.wdBorderBottom].Color = WdColor.wdColorRed; 
1

你可以嘗試使用這個命令:

oTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; 
oTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble; 

使用它們的週期。放完文字後。

+0

謝謝。如果將這些代碼添加到循環中或循環之前/之後,將生成水平和外部垂直線。內部垂直線仍然缺失。 –

7

我用下面的選項來設置所有的邊框和它比設置邊框的每一個細胞相當容易。請注意,獲取Range rng的邏輯適用於VSTO插件,但表格邏輯保持不變。

using Microsoft.Office.Interop.Word; 
    ...... 
    void AddTable() 
    { 
     Range rng = Globals.ThisAddIn.Application.Selection.Range; 
     Table tbl = rng.Tables.Add(rng, 3, 5); //make table at current selection 
     tbl.Range.Font.Name = "Calibri"; 
     tbl.Range.Font.Size = 10.5F; 
     tbl.Range.Font.Bold = 0; 

     //these 2 lines put borders both inside & outside - see result image at end 
     tbl.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; 
     tbl.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; 

     for (r = 1; r <= 3; r++) 
     for (c = 1; c <= 5; c++) 
     { 
      strText = "r" + r + "c" + c; 
      oTable.Cell(r, c).Range.Text = strText; 
     } 

    } 

結果就會像見下表與邊框

enter image description here

希望這有助於。