c# 在 word指定位置插入文字和图片(替换 书签)

原文链接:https://blog.csdn.net/chen1231985111/article/details/125811918

使用 Microsoft.Office.Interop.Word 进行插入, word 文件中 插入 “书签” 。

在com组件中引用 Microsoft.Word.xxx.xx

注意下面的坑:

1. 如果要兼容 office 2007,自己电脑上需要装个07才行 (有可能不需要,我刚开始用2013的dll各种报错,可以先尝试不装)

2. win10 需要设置 .exe 以“管理员身份运行”, 在 属性 -> 兼容性 -> 管理员身份 (勾上)

3. 如果可以,直接把引用的 dll 放到 debug 目录下,引用debug下的dll。

   Microsoft.Office.Interop.Word.Application app = new 
   Microsoft.Office.Interop.Word.Application();
   Microsoft.Office.Interop.Word.Document doc = app.Documents.Add(strDocx);
   app = doc.Application;
   //doc.ActiveWindow.Visible = true;
 
   foreach (Microsoft.Office.Interop.Word.Bookmark bk in doc.Bookmarks)
   {
     if (bk.Name == "MakeSealCompany")
     {
         bk.Range.Text = "插入文字";
     }  
     else if (bk.Name == "qt_d")   
     {
           insereatImage(app, bk, imgPath);  // 插入图片
      }
   }
 
   doc.SaveAs(saveFileDialog1.FileName);
   app.Quit();
 
 
private void insereatImage(Microsoft.Office.Interop.Word.Application app, Microsoft.Office.Interop.Word.Bookmark bk, string imgPath)
{
      bk.Select();
      Microsoft.Office.Interop.Word.Selection sel = app.Selection;
      Microsoft.Office.Interop.Word.InlineShape inlineShape = sel.InlineShapes.AddPicture(imgPath);
 
      //设置图片大小
      inlineShape.Width = 12;
      inlineShape.Height = 12;
}

  

posted @ 2024-02-04 14:19  yinghualeihenmei  阅读(149)  评论(0编辑  收藏  举报