C#操作PPT删除图片

需求:用c#把PPT里删除每一页的图片,而且PPT有三十多页

Spire.Presentation for .NET组件可以轻松删除图片,但这个组件商业版需要购买(没钱),免费版只能操作十页,且自带水印,很明显不符合需求。

剩下的就一种方案,用微软自带的office组件。在项目里引入 Microsoft.Office.Interop.PowerPoint 和 Office。通过NuGet方式下载组件,会自动适配当前.NET FrameWork版本

 

 下面是主要代码:

using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;

using System;

namespace ClearPPTImage
{
    class Program
    {

        /// <summary>
        /// ppt文件地址
        /// </summary>
        private static readonly string filePath = @"E:\bk\demo.pptx";
        static void Main(string[] args)
        {
            Application pptApp = new Application();

            try
            {
                // 以只读方式打开,方便操作结束后保存.
                Presentation presentation = pptApp.Presentations.Open(filePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

                //判断当前PPT是不是空PPT
                if (presentation == null || presentation.Slides.Count <= 0)
                {
                    Console.WriteLine("[Error]当前PPT对象为空");
                    return;
                }


                //注意 Slides的下标要从1开始,如果从0开始会报索引越界
                for (int i = 1; i <= presentation.Slides.Count; i++)
                {
                    Slide slid = presentation.Slides[i];

                    //判断当前ppt页有没有元素
                    if (slid.Shapes.Count <= 0)
                    {
                        continue;
                    }

                    //采用倒叙删除的方式删除图片,这样才能删除干净
                    for (int j = slid.Shapes.Count; j >= 1; j--)
                    {
                        var shapes = slid.Shapes[j];
                        //判断是否是图片
                        if (shapes.Type == MsoShapeType.msoPicture)
                        {
                            shapes.Delete();
                        }

                    }
                }


                //保持到新文件
                presentation.SaveAs(@"E:\bk\demo112.pptx");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[Error]" + ex.Message);
            }
            finally
            {
                //无论什么操作,最后都必须关闭ppt对象
                pptApp.Quit();
            }

            Console.WriteLine("[Success]Success");
            Console.ReadLine();
        }
    }
}

注意点:

1、presentation.Slides的下标要从1开始而不是0,否则会报下标越界错误

2、删除图片或者内容时,要采用倒叙方式删除,否则会有遗留

 

posted @ 2021-04-10 13:06  黑夜中的亮光  阅读(173)  评论(0编辑  收藏  举报