我正在尝试将文本插入到 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/