You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于现有C#文本替换代码实现Word文档图片替换?

使用Microsoft.Office.Interop.Word替换Word文档中的图片

实现思路

和文本替换逻辑不同,图片替换需要遍历文档内的两种图片对象(内联形状/浮动形状),通过预设的标记(比如图片的替代文本)定位目标图片,再删除原有图片并插入新图片,同时保留原位置和尺寸属性。

完整代码示例

using System;
using System.IO;
using Microsoft.Office.Interop.Word;
using System.Windows.Forms;

namespace WordImageReplace
{
    class Program
    {
        static void Main(string[] args)
        {
            // 目标Word文档路径
            string docPath = Path.Combine(Application.StartupPath, @"D:\dpucertificates\DPU.CERTIFICATES\cer_samples\col_ar_male.docx");
            // 待替换的本地图片路径
            string newImagePath = @"C:\your-path\new-image.png"; // 替换为实际图片路径

            Application wordApp = new Application { Visible = true };
            Document targetDoc = null;

            try
            {
                object fileName = docPath;
                // 打开文档
                targetDoc = wordApp.Documents.Open(ref fileName, ReadOnly: false, Visible: true);

                // 处理内联图片(与文本流嵌入的图片)
                foreach (InlineShape inlineImg in targetDoc.InlineShapes)
                {
                    // 匹配预设的替代文本标记(和你文本替换的@标记风格一致)
                    if (inlineImg.AlternativeText == "@avatar@")
                    {
                        // 记录原位置范围
                        Range imgRange = inlineImg.Range;
                        // 删除原有图片
                        inlineImg.Delete();
                        // 在原位置插入新图片
                        targetDoc.InlineShapes.AddPicture(
                            FileName: newImagePath,
                            LinkToFile: false,
                            SaveWithDocument: true,
                            Range: imgRange
                        );
                    }
                }

                // 处理浮动图片(可自由拖动的独立图片)
                foreach (Shape floatImg in targetDoc.Shapes)
                {
                    if (floatImg.AlternativeText == "@avatar@")
                    {
                        // 记录原位置和尺寸
                        float leftPos = floatImg.Left;
                        float topPos = floatImg.Top;
                        float imgWidth = floatImg.Width;
                        float imgHeight = floatImg.Height;

                        // 删除原有图片
                        floatImg.Delete();
                        // 插入新图片并还原位置尺寸
                        Shape newFloatImg = targetDoc.Shapes.AddPicture(
                            FileName: newImagePath,
                            LinkToFile: false,
                            SaveWithDocument: true,
                            Left: leftPos,
                            Top: topPos,
                            Width: imgWidth,
                            Height: imgHeight
                        );
                        // 给新图片设置相同标记,方便后续替换
                        newFloatImg.AlternativeText = "@avatar@";
                    }
                }

                // 保存文档
                targetDoc.Save();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"替换失败:{ex.Message}");
            }
            finally
            {
                // 释放Interop资源,避免Word进程残留
                if (targetDoc != null)
                {
                    object saveOpt = WdSaveOptions.wdSaveChanges;
                    targetDoc.Close(ref saveOpt);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(targetDoc);
                }
                if (wordApp != null)
                {
                    wordApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                }
            }
        }
    }
}

核心注意事项

  • 标记设置:提前在Word中给需要替换的图片设置替代文本(右键图片→格式面板→替代文本),比如用@avatar@作为标记,和你文本替换的标记风格统一,确保精准定位。
  • 覆盖所有图片类型:Word中的图片分为InlineShapes(内联)和Shapes(浮动)两种,代码中同时处理这两类,避免遗漏。
  • 资源清理:必须手动释放Interop对象并关闭Word进程,否则会导致后台残留Word进程占用资源。
  • 图片嵌入:LinkToFile设为false会将图片嵌入文档,SaveWithDocument设为true保证图片随文档保存,不会出现缺失。

内容的提问来源于stack exchange,提问作者noh jalal mohammed mandkany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:57:39