1

我尝试将一些段落自动放入 Word 文档中,但它总是将其放在文档的末尾,而不是放在书签中。

public void createStepTable(Word.Document _myDoc, DataGridView dgv, Testcaselist _testcaselist)
    {
        int namecount = 1;
        object oMissing = System.Reflection.Missing.Value;

        Word.Bookmark myBookmark = _myDoc.Bookmarks.get_Item("TextMarkeEinzelheiten");
        MessageBox.Show(myBookmark.Start.ToString());
        Word.Range myRange = _myDoc.Range(myBookmark.Start,myBookmark.End);

        Word.Field myfield = _myDoc.Fields.Add(myRange);
        Word.Selection mySelection = myRange.Se




        foreach (Testchannellist testChannelListToFind in _testcaselist.Testchannellist)
        {

            Word.Paragraph pText = _myDoc.Paragraphs.Add(myRange);         
            pText.Format.SpaceAfter = 10f;
            pText.Range.Text = String.Format("This is headline #{0}",namecount);
            pText.Range.InsertParagraphAfter();

            int stepcount = 0;
            foreach (Teststeplist testStepListToFind in testChannelListToFind.Teststeplist)
            {
                var sText = _myDoc.Paragraphs.Add(myRange);  
                sText.Format.SpaceAfter = 10f;
                sText.Range.Text = String.Format("This is testfall #{0}", stepcount);
                sText.Range.InsertParagraphAfter();


                for (int i = 0; i < testStepListToFind.requirementlist.Count; i++)
                {
                    var rText = _myDoc.Paragraphs.Add(myRange);  
                    rText.Range.ListFormat.ApplyBulletDefault();
                    rText.Range.InsertBefore(testStepListToFind.requirementlist[i].ToString() );
                }

                dgv.DataSource = testStepListToFind.repTest;
                var tText = _myDoc.Paragraphs.Add(myRange);                    
                tText.Format.SpaceAfter = 10f;
                tText.Range.Text = String.Format("This is Tabelle #{0}", stepcount );
                tText.Range.InsertParagraphAfter();
                stepcount++;


            }


        }

    }

所有那些自动创建的段落都应该在“TextMarkeEinzelheiten”书签中,但每次尝试都会一团糟。

4

1 回答 1

1

首先确保书签确实存在于您正在使用的文档/模板中。

这是我用来插入表格的代码。段落应该相同

            Range range = null;
            object pageBookmark = "TextMarkeEinzelheiten";
            if (_myDoc.Bookmarks.Exists(pageBookmark.ToString()))
            {
                range = _myDoc.Bookmarks.get_Item(ref pageBookmark).Range;
                Bookmark bookmark = _myDoc.Bookmarks.get_Item(ref pageBookmark);
                bookmark.Select();
            }
            else
            {
                range = range ?? _myDoc.Range(0, 0);
            }
            Word.Paragraph pText = _myDoc.Paragraphs.Add(myRange);

先试试这段代码,不要使用 for 循环。一旦你得到一个段落正确调整代码,以便在循环中插入新段落时更新范围和选择。

祝你好运 :)

于 2013-10-27T23:02:51.667 回答