2012-08-28 68 views
1

我正在編寫一個軟件,它需要用圖像或文本替換圖像。 我發現一些代碼替換圖像的圖像,它工作正常。 我想調整此代碼,以便我還可以用文本替換圖像。 我知道有更好的方法來做到這一點,但我特別需要使用Interlope來完成。 任何幫助,將不勝感激。C#Word自動化:用文本替換圖片

using System.Collections.Generic; 
using Word = Microsoft.Office.Interop.Word; 

namespace WordExample 
{ 
class WordExample 
{ 
    #region Constructor 
    public WordExample() 
    { 
     WordApp = new Microsoft.Office.Interop.Word.Application(); 
    } 
    #endregion 

    #region Fields 
    private Word.Application WordApp; 
    private object missing = System.Reflection.Missing.Value; 
    private object yes = true; 
    private object no = false; 
    private Word.Document d; 
    private object filename = @"C:\FullPathToFile\example.doc"; 
    #endregion 

    #region Methods 
    public void UpdateDoc() 
    { 
     d = WordApp.Documents.Open(ref filename, ref missing, ref no, ref missing, 
      ref missing, ref missing, ref missing, ref missing, ref missing, 
      ref missing, ref missing, ref yes, ref missing, ref missing, ref missing, ref missing); 
     List<Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>(); 
     foreach (Word.InlineShape s in d.InlineShapes) 
     { 
      if (s.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture) 
      { 
       ranges.Add(s.Range); 
       s.Delete(); 
      } 
     } 
     foreach (Word.Range r in ranges) 
     { 
      r.InlineShapes.AddPicture(@"c:\PathToNewImage\Image.jpg", ref missing, ref missing, ref missing); 
     } 
     WordApp.Quit(ref yes, ref missing, ref missing); 
    } 
    #endregion 
} 
} 

回答

2

我是新使用的詞intelop現在知道了。解決方案非常簡單並且正在工作。只需添加以供將來參考。 BO.image是一個包含數據和數據類型的簡單對象。

private static void FindAndReplaceImages(Word.Document d, BO.ImageReplace image) 
{ 
    object missing = System.Reflection.Missing.Value; 
    List<Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>(); 
    foreach (Word.InlineShape s in d.InlineShapes) 
    { 
     if (s.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture) 
     { 
      ranges.Add(s.Range); 
      s.Delete(); 
     } 
    } 

    foreach (Word.Range r in ranges) 
    { 
     if (image.DataType == "image")//then image.Data is a location on disk 
     { 
      r.InlineShapes.AddPicture(image.Data, ref missing, ref missing, ref missing); 
     } 
     else if(image.DataType == "word")//then image.Data is a string 
     { 
      r.InsertBefore(image.Data); 
     } 
    } 
}