62,046
社区成员
发帖
与我相关
我的任务
分享
Microsoft.Office.Interop.Word.ApplicationClass appWord = null;//应用程序
Microsoft.Office.Interop.Word.DocumentClass doc = null;//文档
try
{
appWord = new ApplicationClass();
appWord.Visible = false;
object objTrue = true;
object objFalse = false;
//object objTemplate = "template.dot ";//模板绝对路径
object objTemplate = Server.MapPath("template.dot ");//模板相对路径
object objDocType = WdDocumentType.wdTypeDocument;
doc = (DocumentClass)appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
//生成word文档
object sq_depName = "depName"; //部门名
// 给书签赋值
doc.Bookmarks.get_Item(ref sq_depName).Range.Text = wr.DepName;
#region//生成word
string fn = CreateFileName();
object filename = Server.MapPath(".") + fn;
//object filename = @"c:\test.doc";
object miss = System.Reflection.Missing.Value;
doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
#endregion
//退出word,同时释放资源
object missingValue = Type.Missing;
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
/*错误地方*/doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
appWord.Application.Quit(ref miss, ref miss, ref miss);
doc = null;
appWord = null;
}
catch (System.Exception ex)
{
//捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
string aa = ex.ToString();
object miss = System.Reflection.Missing.Value;
object missingValue = Type.Missing;
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
appWord.Application.Quit(ref miss, ref miss, ref miss);
doc = null;
appWord = null;
}