如何在文档的末尾插入文本
我试图在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"); } }
您必须使用append方法在同一行中添加文本而不是输入下一行Ex:
File.AppendAllText(@"c:pathfile.txt", textBox1.Text);
这可能有所帮助
上述就是C#学习教程:如何在文档的末尾插入文本分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/987101.html