c# - 如何在文档末尾插入文本

标签 c# text ms-word

我正在尝试将文本插入到 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");
        }
    }

最佳答案

下面代码中的第 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");
    }
}

关于c# - 如何在文档末尾插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32693480/

相关文章:

c# - 系统和自定义命名空间之间的区别

c# - 为图像文件或一般文件设置默认构建操作

java - Swing 文本 API : Override LabelView with different string length?

haskell - 使用惰性文本和字节字符串处理非常大的文本文件

c# - 如何在 C# 中将文本从 RTF 插入到 Word 文档

java - 在本地保存文档时,是否可以将本地 Word 文档编辑器上所做的编辑同步到其中央存储库文档(db 文档)?

c# - 解释 MVC 授权属性如何执行类似 AOP 的操作

python - 如何计算 Pandas 数据框的大写和小写

asp.net - 在 Web 表单中编辑文档(DOC、DOCX、RTF、TXT)

c# - 我可以在 WPF 中使用 "defeat"SizeToContent 的面板吗?