C # locate a location in a Word document and insert text

Source: Internet
Author: User

Use bookmarks to locate the specified location of a Word document (three methods)
First, set and name the bookmarks in the Word documents. (assume that a bookmark named "bm_test" is created)

Then use C # To operate the word

Using MSWord = Microsoft. Office. InterOP. word;

Private MSWord. Application wordapp; // word ApplicationProgramVariable
Private MSWord. Document worddoc; // Word document variable
Private object nothing = missing. value;
// Initialization
Wordapp = new MSWord. applicationclass ();
Worddoc = wordapp. Documents. Add (ref nothing, ref nothing );
// Open Word
Object filename = strpath;
Object readonly = false;
Object isvisible = true;
Worddoc = wordapp. Documents. Open (ref filename, ref nothing, ref readonly,
Ref nothing, ref nothing,
Ref nothing, ref isvisible, ref nothing,
Ref nothing, ref nothing, ref nothing );

Object BK = "bm_test ";

Method 1: use the word application variable. In this method, make sure that the isvisible value is true in wordapp. Documents. open ().
If (wordapp. activedocument. bookmarks. exists ("bm_test "))
{
Wordapp. activedocument. bookmarks. get_item (ref BK). Select ();
Wordapp. selection. typetext ("insert text"); // insert text
}

Method 2: Use Word document Variables
If (worddoc. bookmarks. exists ("bm_test "))
{
Worddoc. bookmarks. get_item (ref BK). range. Text = "insert text"; // insert text
}

Method 3: Use the Goto function to jump to the specified bookmarks
Object bookmarkname = "bm_test ";
Object what = MSWord. wdgotoitem. wdgotobookmark;
Worddoc. activewindow. selection. Goto (ref what, ref nothing, ref nothing, ref bookmarkname );
Worddoc. activewindow. selection. typetext ("Hello! ");

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.