花了好大的功夫才解決這個(gè)問題,現(xiàn)在拿出來與大家分享。
C# 生成word文檔時(shí)彈出“Normal.dotm被另一程序或用戶使用”的主要原因是在生成word文檔后關(guān)閉word時(shí)發(fā)生的問題。
//出現(xiàn)提示框前我們通常使用的關(guān)閉word代碼為
oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
因此,解決方法如下:
//在關(guān)閉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);
這給一個(gè)完整的例子
首先要記得引用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文檔選擇“插入”->“書簽”試著定義一下,或查找相關(guān)word的資料
object oBookMark;
oBookMark = "guest_num";//這里是定義好的書簽名稱“guest_num”表示客戶編號(hào)
oDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = "這里是要替換的值";
oBookMark = "同上方法"; //多個(gè)書簽,與以上方法一樣
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中的內(nèi)容的代碼,呵呵
oDoc.ActiveWindow.Selection.WholeStory();
oDoc.ActiveWindow.Selection.Copy();
//從剪切板獲取數(shù)據(jù)
IDataObject data = Clipboard.GetDataObject();
//this.richTextBox1.Text=data.GetData(DataFormats.Text).ToString();//顯示文檔內(nèi)容
*/
//關(guān)閉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, "失敗");
}
聯(lián)系客服