我正在尝试在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");
}
}
答案 0 :(得分: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");
}
}
答案 1 :(得分:0)
您必须使用append方法在同一行中添加文本,而不是输入下一行 例如:
File.AppendAllText(@"c:\path\file.txt", textBox1.Text);