黑马程序员技术交流社区
标题:
C#中追加写入word方法(二次不覆盖)
[打印本页]
作者:
白建新
时间:
2012-4-5 11:06
标题:
C#中追加写入word方法(二次不覆盖)
/// 追加写入word
/// </summary>
/// <param name="InsertText">需要写入的字符串</param>
public void WriteToWord(string InsertText)
{
Word.ApplicationClass app = null;
Word.Document doc = null;
object missing = System.Reflection.Missing.Value;
object FileName = m_FilePath;//@"E:\学习试验项目\ReadFromWordDoc\test.doc";
object readOnly = false;
object isVisible = false;
try
{
app = new Word.ApplicationClass();
doc = app.Documents.Open(ref FileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref isVisible, ref missing,
ref missing, ref missing, ref missing);
//激活word文档
doc.Activate();
//追加到最后一段(段落是按照 \n 来作为标志的)
doc.Paragraphs.Last.Range.Text = InsertText + "\n";//加个结束符(增加一段),否则再次插入的时候就成了替换.
//保存
doc.Save();
}
catch(Exception ex)
{
throw ex;
}
finally
{
if (doc != null)
{
try
{
doc.Close(ref missing, ref missing, ref missing);
}
catch
{}
doc = null;
}
if (app != null)
{
try
{
app.Quit(ref missing, ref missing, ref missing);
}
catch
{}
app = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2