-->

C# Word Automation : Replace picture with Text

2019-06-07 05:28发布

问题:

I am programming a software and it requires images to be replaced with either images or text. I found some code to replace images with images it works fine. I want to tweak this code so that i can also replace images with text. I know there are better ways to do it but I specifically need it done using Interlope. Any help would be appreciated.

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
 }
}

回答1:

I am new to using word intelop so did now know. The solution was quite simple and is working. Just adding to use for future reference. BO.image is a simple object containing data and dataType.

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);
        }
    }
}