因项目需要,给word文档的书签赋值,框架没有相关内容,于是自己上网加上查看文档,成功搞定该功能。下面是我的实现过程:
首先需要引用nuget包: Microsoft.Office.Interop.Word,我下载的是12.0.0版本的,刚开始下载的15.0.0版本的无法使用,暂时不知道为什么,有空研究一下;然后就是代码实现:
/// <summary> /// 版 本 /// Copyright (c) 2018-2018 /// 创建人:Yu /// 日 期:2018.04.17 /// word操作 /// </summary public class WordHelp { ApplicationClass wordApp = new ApplicationClass(); Document doc; /// <summary> /// 生成文件存放地址 /// </summary> public string newPath { get; set; } /// <summary> /// 生成的新文件文件夹路径 /// </summary> public string newDicPath { get; set; } /// <summary> /// 无参构造方法 /// </summary> public WordHelp() { } /// <summary> /// 打开模板 /// </summary> /// <param name="fileName">文档名</param> public WordHelp(string filePath) { try { var FileLocation = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase; var oldPath = FileLocation + filePath; RandomPW randomPW = new RandomPW(); var random = randomPW.GetRandomPW(10); newPath = FileLocation + "new\" + random + "\" + filePath; while (!File.Exists(newPath)) { random = randomPW.GetRandomPW(10); newPath = FileLocation + "new\" + random + "\" + filePath; Directory.CreateDirectory(FileLocation + "new\" + random + "\"); File.Copy(oldPath, newPath); } newDicPath = FileLocation + "new\" + random + "\"; object fileobj = newPath; object nullobj = System.Reflection.Missing.Value; //打开指定文件(不同版本的COM参数个数有差异,一般而言除第一个外都用nullobj就行了) doc = wordApp.Documents.Open(ref fileobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj); } catch (Exception e) { Close(); DelDic(newPath); } } /// <summary> ///获取word的书签集合 /// </summary> /// <returns></returns> public List<string> GetBookmarks() { List<string> bookmarks = new List<string> { }; foreach (Bookmark bk in doc.Bookmarks) { bookmarks.Add(bk.Name); } return bookmarks; } /// <summary> /// 给书签赋值 /// </summary> /// <param name="key">书签名</param> /// <param name="value">书签值</param> public void SetBookmarks(object key, string value) => doc.Bookmarks.get_Item(ref key).Range.Text = value; /// <summary> /// 关闭io /// </summary> public void Close() => doc.Close(); /// <summary> /// 删除生成的文件 /// </summary> /// <param name="filePath"></param> public void DelDic(string filePath)=> Directory.Delete(filePath, true); }
然后发现程序运行时还是报错,
未加载加程序集Microsoft.Office.Interop.Word………………
查看了一下,原来是我没有安装office,我安装的是2007版本,安装之后可以使用。