【问题标题】:How to Insert text in the end of the document如何在文档末尾插入文本
【发布时间】:2023-04-06 16:18:01
【问题描述】:

我正在尝试将文本插入到 word 文档中。但是每当我执行我的代码时,我在文本框中输入的文本总是在开头添加。我无法在文档末尾插入文本。我也无法使用Range 解决此问题。

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");
        }
    }

【问题讨论】:

  • 你试过InsertAfter吗?
  • 使用这两个命令移动到文档的末尾:ActiveDocument.Characters.Last.Select 然后Selection.Collapse
  • 谢谢..!!! ActiveDocument.Characters.Last.SelectSelection.Collapse cmets 工作..!!!

标签: c# text ms-word


【解决方案1】:

下面代码中的第 1 行和第 2 行对我有帮助。 以下代码运行良好。

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");
    }
}

【讨论】:

    【解决方案2】:

    您必须使用 append 方法在同一行中添加文本,而不是在下一行输入 例如:

    File.AppendAllText(@"c:\path\file.txt", textBox1.Text);
    

    This might help

    【讨论】:

    • 他正在处理一个单词对象,而不是一个简单的文本文件。
    • 我只是试图通过这个例子来解释append方法的使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2011-12-08
    • 1970-01-01
    相关资源
    最近更新 更多