C# 生成word时弹出 Normal.dotm 被占用的解决方案

发布时间:2010年07月28日      浏览次数:850 次
花了好大的功夫才解决这个问题,现在拿出来与大家分享。
C# 生成word文档时弹出“Normal.dotm被另一程序或用户使用”的主要原因是在生成word文档后关闭word时发生的问题。
//出现提示框前我们通常使用的关闭word代码为
oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
因此,解决方法如下:
//在关闭word文档处,使用以下代码即可。
object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
oDoc.Close(ref saveOption, ref oMissing, ref oMissing);
oWord.Quit(ref saveOption, ref oMissing, ref oMissing);
==================================================================
附一个我常用的调用word模板替换内容并生成新的word文档的代码
==================================================================
首先要记得引用word
1、添加引用->COM->Microsoft Word 11.0 Object Library
2、在.cs文件中添加 using Word;
3、下面是生成word的代码
try
{
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application oWord;
Microsoft.Office.Interop.Word._Document oDoc = null;
object oTemplate = System.Windows.Forms.Application.StartupPath + "\test_mode.docx"; //打开模板文件
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = false;
try
{
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
}
catch (Exception Ex)
{
MessageBox.Show("模板文件打开失败!\n\n原因:\n" + Ex.Message, "失败");
return;
}
//替换模板文件中定义好的“书签”,如果不懂“书签”怎么回事的自已打开word文档选择“插入”->“书签”试着定义一下,或查找相关word的资料
object oBookMark;
oBookMark = "guest_num";//这里是定义好的书签名称“guest_num”表示客户编号
oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "这里是要替换的值";
oBookMark = "同上方法"; //多个书签,与以上方法一样
oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "同上方法";
object oFilename = System.IO.Directory.GetCurrentDirectory() + "\test.docx";//指定生成新word文档的路么及名称
try
{
oDoc.SaveAs(ref oFilename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);//生成word文档
}
catch (Exception Ex)
{
MessageBox.Show("文件生成失败!\n\n原因:\n" + Ex.Message, "失败");
return;
}
/*
这里面是我测试输出显word中的内容的代码,呵呵
oDoc.ActiveWindow.Selection.WholeStory();
oDoc.ActiveWindow.Selection.Copy();
//从剪切板获取数据
IDataObject data = Clipboard.GetDataObject();
//this.richTextBox1.Text=data.GetData(DataFormats.Text).ToString();//显示文档内容
*/
//关闭word文档
object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
oDoc.Close(ref saveOption, ref oMissing, ref oMissing);
oWord.Quit(ref saveOption, ref oMissing, ref oMissing);
MessageBox.Show("word文件生成成功!", "成功");
}
catch (Exception Ex)
{
MessageBox.Show("文件生成失败!\n\n原因:\n" + Ex.Message, "失败");
}
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!