Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - How to Insert text in the end of the document

I am trying to insert text into the word document. But whenever i execute my code the text enter by me in the text box is always added in the beginning. I am unable to insert the text in the end of the document. I am unable to fix this using Range also.

private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            if (textBox1.Text != "")
            {
                Microsoft.Office.Interop.Word._Application oWord;
                object oMissing = Type.Missing;
                oWord = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = false;
                oWord.Documents.Open(filePath);
                oWord.Selection.TypeText(textBox1.Text);
                oWord.ActiveDocument.Save();
                oWord.Quit();
                MessageBox.Show("The text is inserted.");
                textBox1.Text = "";
            }
            else
            {
                MessageBox.Show("Please give some text in the text box");
            }
        }
        catch(Exception)
        {
            MessageBox.Show("Please right click on the window and provide the path");
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Line 1 and Line 2 in the below code helps me. The following code works fine.

private void button2_Click(object sender, EventArgs e)
{
    try
    {
        if (textBox1.Text != "")
        {
            Microsoft.Office.Interop.Word._Application oWord;
            object oMissing = Type.Missing;
            oWord = new Microsoft.Office.Interop.Word.Application();
            oWord.Visible = false;
            oWord.Documents.Open(filePath);
            oWord.ActiveDocument.Characters.Last.Select();  // Line 1
            oWord.Selection.Collapse();                     // Line 2
            oWord.Selection.TypeText(textBox1.Text);
            oWord.ActiveDocument.Save();
            oWord.Quit();
            MessageBox.Show("The text is inserted.");
            textBox1.Text = "";
        }
        else
        {
            MessageBox.Show("Please give some text in the text box");
        }
    }
    catch(Exception)
    {
        MessageBox.Show("Please right click on the window and provide the path");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...