Microsoft.Office.Interop.PowerPoint 根据模板导出PowerPoint

环境:Visual Studio 2015


场景:现有一个PPT模板,需要把业务数据插到PPT里面。

思路:在PPT模板里面做好标识,然后建一个Dictionary,key是PPT里面的标识,value是要替换的内容,通过Microsoft.Office.Interop.PowerPoint把数据插入PPT模板。


实施:

需要要导入Microsoft.Office.Interop.PowerPoint、Microsoft.Office.Core,用[NuGet]管理就好了。

引入命名空间

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

代码:

数据组织

            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            keyValues.Add("idField", "101");
            keyValues.Add("titleField", "测试101");
            keyValues.Add("nameField", "郑同学");
            keyValues.Add("funField", "");
            keyValues.Add("proField", "");
            keyValues.Add("sproField", "");

替换PPT文本

using System;
using System.Collections.Generic;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;

namespace ConsoleApplication3
{
    public class PowerPointHelper
    {
        public static string ReplacePowerPoint(string filePath, Dictionary<string, string> keyValues)
        {
            string path = "";
            Application pptApp;
            Presentations presentations = null;
            Presentation presentation = null;
            pptApp = new Application();
            try
            {
                presentations = pptApp.Presentations;
                //打开PPT
                presentation = presentations.Open(filePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                //替换模板PPT中的文本
                foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in presentation.Slides)
                {
                    foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
                    {
                        ReplaceShapeText(shape, keyValues);
                    }
                }
                
                //保持文件
                path = AppDomain.CurrentDomain.BaseDirectory + "PPT/test-" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".pptx";
                presentation.SaveAs(AppDomain.CurrentDomain.BaseDirectory + path);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                try
                {
                    presentation.Close();
                    pptApp.Quit();
                }
                catch (Exception) { }
            }
            return path;
        }

        /// <summary>
        /// 替换PowerPoint TextBox的内容
        /// </summary>
        /// <param name="shape"></param>
        /// <param name="dicKeyWordList"></param>
        public static void ReplaceShapeText(Microsoft.Office.Interop.PowerPoint.Shape shape, Dictionary<string, string> dicKeyWordList)
        {
            if (dicKeyWordList != null && dicKeyWordList.Count > 0)
            {
                if (shape.Type == MsoShapeType.msoGroup)
                {
                    foreach (Microsoft.Office.Interop.PowerPoint.Shape sh in shape.GroupItems)
                    {
                        ReplaceShapeText(sh, dicKeyWordList);
                    }
                }
                if (shape.HasTextFrame != Microsoft.Office.Core.MsoTriState.msoTrue)
                {
                    return;
                }
                foreach (string strKeyWord in dicKeyWordList.Keys)
                {
                    TextRange textRange = shape.TextFrame.TextRange.Find(strKeyWord, 0, MsoTriState.msoTriStateMixed, MsoTriState.msoFalse);
                    if (textRange != null)
                    {
                        shape.TextFrame.TextRange.Text = shape.TextFrame.TextRange.Text.Replace(strKeyWord, dicKeyWordList[strKeyWord]);
                    }
                }
            }
        }

    }
}

另外可能有事还需要插入图片之类的,请看下面

        public static string EditPowerPoint(string filePath, Dictionary<string, string> keyValues)
        {
            string path = "";
            Application pptApp;
            Presentations presentations = null;
            Presentation presentation = null;
            pptApp = new Application();
            try
            {
                presentations = pptApp.Presentations;
                presentation = presentations.Open(filePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                //插入图片
                if (keyValues.ContainsKey("UserProfileUrl") && keyValues["UserProfileUrl"] != null)
                {
                    try
                    {
                        presentation.Slides[1].Shapes.AddPicture(keyValues["UserProfileUrl"], Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 588, 88, 115, 98);
                    }
                    catch { }
                }
                if (keyValues.ContainsKey("Image1") && keyValues["Image1"] != null)
                {
                    try
                    {
                        presentation.Slides[1].Shapes.AddPicture(keyValues["Image1"], Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 5, 290, 238, 206);
                    }
                    catch { }
                }
                if (keyValues.ContainsKey("Image2") && keyValues["Image2"] != null)
                {
                    try
                    {
                        presentation.Slides[1].Shapes.AddPicture(keyValues["Image2"], Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 370, 290, 238, 206);
                    }
                    catch { }
                }
                //Hyperlink h = 
                path = AppDomain.CurrentDomain.BaseDirectory + "PPT/test-" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".pptx";
                presentation.SaveAs(AppDomain.CurrentDomain.BaseDirectory + path);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                try
                {
                    presentation.Close();
                    pptApp.Quit();
                }
                catch (Exception) { }
            }
            return path;
        }

注意了,Slides下标是从1开始的


2019年6月18日 更新

关于怎么向PPT中添加超链接,目前好像是不能直接往PPT里面插入超链接的,但是可以预先在PPT设好超链接,然后在代码中替换Hyperlink对象的地址和显示文本,通过这种方式达到我们的目的。

                foreach (Hyperlink h in presentation.Slides[1].Hyperlinks)
                {
                    if (h.Address == "http://test/Home/Login" && keyValues.ContainsKey("AttachmentUrl"))
                    {
                        h.Address = keyValues["AttachmentUrl"];//"https://www.baidu.com/";
                        h.TextToDisplay = keyValues["AttachmentField"];
                    }
                }

猜你喜欢

转载自blog.csdn.net/u012835032/article/details/92061777