生成表并将其添加到特定书签Office Interop Word

时间:2018-04-30 06:59:57

标签: c# datatable ms-word office-interop

要求是将Office.Interop.Word表添加到文档

中的特定书签

以下片段

     // using Microsoft.Office.Interop.Word;
        _Application word = new Application();
        Document doc = word.Documents.Open(oTemplate);

        //Selecting a Bookmark
        doc.Bookmarks["Bookmarks1"].Select();
        word.Selection.TypeText("adding Text to it"); // Success

现在到表

  ////Create a 5X5 table and insert some dummy record

        Microsoft.Office.Interop.Word.Paragraph para1 = doc.Content.Paragraphs.Add();
        Microsoft.Office.Interop.Word.Table firstTable = doc.Tables.Add(para1.Range, 5, 5);

        firstTable.Borders.Enable = 1;
        foreach (Row row in firstTable.Rows)
        {
            foreach (Cell cell in row.Cells)
            {
                //Header row
                if (cell.RowIndex == 1)
                {
                    cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                    cell.Range.Font.Bold = 1;
                    //other format properties goes here
                    cell.Range.Font.Name = "verdana";
                    cell.Range.Font.Size = 10;
                    //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;                            
                    cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                    //Center alignment for the Header cells
                    cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                    cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                }
                //Data row
                else
                {
                    cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                }
            }
        }

我需要在特定书签上添加表格....

1 个答案:

答案 0 :(得分:0)

下面的代码完成了诀窍

////Create a 5X5 table and insert some dummy record
Microsoft.Office.Interop.Word.Range wrdRng = doc.Bookmarks.get_Item(ref test).Range;
//Microsoft.Office.Interop.Word.Paragraph para1 = doc.Content.Paragraphs.Add();
Microsoft.Office.Interop.Word.Table firstTable = word.Selection.Tables.Add(wrdRng, 5, 5);