C#字自动化:替换文字图片(C# Word Automation : Replace picture

2019-09-21 19:52发布

我编程软件,它需要的图像与任何图像或文字来代替。 我发现一些代码来替换图像,它工作正常图像。 我想调整这个代码,这样我也可以用文字代替图片 。 我知道有更好的方法来做到这一点,但我特别需要它的使用侵犯完成。 任何帮助,将不胜感激。

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

Answer 1:

我是新来使用文字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);
        }
    }
}


文章来源: C# Word Automation : Replace picture with Text