问题:我需要在代码里面替换word的书签以便数据显示到word里面去,然后我在本机实现了这个功能,结果把项目放服务器就报错,刚开始我以为是服务器word版本问题,结果换成跟本机一样的也不行,求解什么原因。
报错代码:
下面贴上我的代码:
DAL.htglDAL htd = new DAL.htglDAL();
int id = DTRequest.GetQueryInt("id"); //获取id
int type = DTRequest.GetQueryInt("type"); //获取type判断用户点的是导出word还是查看详细:0为查看详细,1为导出wrod
show_world sw = new show_world();
string fileName = "imageHTS/htmb.doc";
DateTime befoTime = DateTime.Now;
Word.Application word = new Word.ApplicationClass(); // 定义一个Word.Application 对象
if (type == 0)
{
DataTable dt = htd.GetModelDateset(id).Tables[0];
sw.OpenDoc(dt, befoTime, fileName, ref word, 1);
ConvertWordPDF1(System.Web.HttpContext.Current.Server.MapPath("imageHTS/" + dt.Rows[0]["xmmc"] + ".doc"), System.Web.HttpContext.Current.Server.MapPath("imageHTS/" + dt.Rows[0]["xmmc"] + ".pdf"));
Priview(this, "imageHTS/" + dt.Rows[0]["xmmc"] + ".pdf");
}
—————————————————————————————————————
show_word.cs代码:
public class show_world
{
DateTime afterTime;
public Word.Document OpenDoc(DataTable dt, DateTime beforeTime, string strDocPath, ref Microsoft.Office.Interop.Word.Application WordApp, int flag)
{
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strDocPath)))
{
return null;
}
object missing = System.Reflection.Missing.Value;
object fileName = (object)System.Web.HttpContext.Current.Server.MapPath(strDocPath);
object isVisible = true;
object readOnly = false;
//Make word visible, so you can see what's happening
//WordApp.Visible = false;
//通过open创建一个Word.Document的实例
Word.Document doc = WordApp.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);
try
{
foreach (Word.Bookmark BM in doc.Bookmarks) //这是最关键的地方:对文档的所有书签进行便利匹配
{
switch (BM.Name)
{
case "htbh":
BM.Select();
BM.Range.Text = dt.Rows[0]["htbh"].ToString();
break;
case "xmmc": //替换Advice书签的内容,其他一样
BM.Select();
BM.Range.Text = dt.Rows[0]["xmmc"].ToString();
break;
}
}
string pathname = dt.Rows[0]["xmmc"].ToString() + ".doc";
object fn = (object)System.Web.HttpContext.Current.Server.MapPath("imageHTS/" + pathname);
doc.SaveAs(ref fn, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);//这里是另存为一个一个文件
this.afterTime = DateTime.Now;
KillExcelProcess(beforeTime, "WINWORD");
return doc;
}
catch (Exception Ex)
{
throw new Exception(Ex.Message);
}
}
/// <summary>
/// 结束启动的Office程序进程
/// </summary>
/// <param name="strAppName">Office程序进程名</param>
protected virtual void KillExcelProcess(DateTime beforeTime, string strAppName)
{
System.Diagnostics.Process[] myProcesses;
DateTime startTime;
myProcesses = System.Diagnostics.Process.GetProcessesByName(strAppName);
//得不到Excel进程ID,暂时只能判断进程启动时间
foreach (System.Diagnostics.Process myProcess in myProcesses)
{
try
{
startTime = myProcess.StartTime;
if (startTime > beforeTime && startTime < afterTime)
{
myProcess.Kill();
return;
}
}
catch
{
}
}
}
}