C#向Word文档中的书签赋值

时间:2021-11-13 03:17:06

1:在给定的word模板中向需要赋值的内容加入书签

2:在管理NuGet程序包中引用Microsoft.Office.Interop.Word

3:object oMissing = System.Reflection.Missing.Value;             //创建一个Word应用程序实例            

Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();             //设置为不可见            

oWord.Visible = false;             //模板文件地址            

string file = "审理意见书.doc";            

object oTemplate = Path.Combine(context.Server.MapPath("/Audit/"), file); ;//模板路径             //以模板为基础生成文档              Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);           

try {                       

object[] oBookMark = new object[6];           //声明书签数组  

   //赋值书签名      

oBookMark[0] = "ProjectName";  //项目名称               

    oBookMark[1] = "SubmitDate";  //送审时间                

  oBookMark[2] = "ClosedTime";  //结审日期                

  oBookMark[3] = "PersonnelDate";  //审理人员(自动加入姓名和日期)                

  oBookMark[4] = "RpersonnelDate";  //审理机构负责人(姓名和日期)                 

  oBookMark[5] = "ApersonnelDate";  //总审计师意见(姓名和日期)

//赋值任意数据到书签的位置                 

     oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text =”项目名称“;                

   oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text = ”2016-10-15“ ;                             

   oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text = ”2016-10-15“ ;                   

   oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text = ”2016-10-15“;                

   oDoc.Bookmarks.get_Item(ref oBookMark[4]).Range.Text = ”2016-10-15“;               

  oDoc.Bookmarks.get_Item(ref oBookMark[5]).Range.Text = "同意(输入)";               

  //生成word ,并保存在文件夹中             

  string filen = info.ProjectName + "-审理意见书.doc";                

  object filename = context.Server.MapPath("/Files/") + filen;               

 string path = "/Files/" + filen;             

   oDoc.SaveAs(ref filename, 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);

oDoc.Close(ref oMissing, ref oMissing, ref oMissing);                 //关闭word                 

   oWord.Quit(ref oMissing, ref oMissing, ref oMissing);               

  oDoc = null;                

  oWord = null;