zoukankan      html  css  js  c++  java
  • C# PPT Operator

    来自:http://blog.csdn.net/lxzh12345/article/details/47047491

    最近在写一个工具,设计到将界面内容到处到PPT中,且导出的内容能够编辑。网上搜了很多C#导出到PPT的方法,无非都是官方文档稍微改改到处传。因此结合MSDN的文档外加自己的摸索,将对PPT的操作封装了一下,里面包含几个常用的方法:添加文本框、直线、箭头、矩形、图片。后面有机会再继续扩展。

    注:这里只给出了封装的类,直接使用可能会有问题,记得添加Office2007对应组件的引用。

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using Microsoft.Office.Core;  
    6. using PPT = Microsoft.Office.Interop.PowerPoint;  
    7. using System.Windows;  
    8. using System.Collections;  
    9. using System.Windows.Forms;  
    10. using System.IO;  
    11. using System.Reflection;  
    12. using Tools.functionModel.file;  
    13. using System.Drawing;  
    14. using System.Drawing.Imaging;  
    15. //using System.Windows.Controls;  
    16.    
    17. namespace Tools.baseModel.common {  
    18.     /// <summary>  
    19.     /// PPT文档操作实现类.  
    20.     /// </summary>  
    21.     public class pptBase {  
    22.         private string temPath = "";  
    23.         private string pptPath = "";  
    24.   
    25.         #region=========基本的参数信息=======  
    26.         PPT.Application pptApp;                 //PPT应用程序变量  
    27.    
    28.         public PPT.Application PptApp {  
    29.             get { return pptApp; }  
    30.             set { pptApp = value; }  
    31.         }  
    32.         PPT.Presentation pptDoc;                //PPT文档变量  
    33.         PPT.Slides pptSlides = null;  
    34.         PPT.Slide pptSlide = null;  
    35.         private int pageCount=0;  
    36.         #endregion  
    37.    
    38.         public PPT.Shapes Shapes {  
    39.             get { return pptSlide.Shapes; }  
    40.         }  
    41.    
    42.    
    43.         public pptBase(string path) {  
    44.             this.temPath = commonPath.fiberFolder + "/other/template.pot";  
    45.             this.pptPath = path;  
    46.             //如果已存在,则删除  
    47.             if (File.Exists((string)pptPath)) {  
    48.                 File.Delete((string)pptPath);  
    49.             }  
    50.             FileInfo file = new FileInfo(this.temPath);  
    51.             pptApp = new PPT.Application();    //初始化  
    52.             pptApp.Visible = MsoTriState.msoTrue;  
    53.             pptDoc = pptApp.Presentations.Open(file.FullName, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);  
    54.             pptSlides = pptDoc.Slides;  
    55.             //pptDoc = pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);  
    56.         }  
    57.    
    58.         public void AddPage() {  
    59.             pageCount++;  
    60.             //pptDoc.Slides.Add(pageCount, PPT.PpSlideLayout.ppLayoutText);  
    61.             pptSlide = pptSlides.Add(pageCount, PPT.PpSlideLayout.ppLayoutTitleOnly);  
    62.         }  
    63.    
    64.         public void InsertPage(int index) {  
    65.             PPT.CustomLayout ppLayout = pptSlide.CustomLayout;  
    66.             pptSlide = pptSlides.AddSlide(index, ppLayout);  
    67.             pageCount++;  
    68.         }  
    69.   
    70.   
    71.         #region 添加文本框  
    72.         public PPT.Shape drawText(PPT.Shapes shapes, pptText textBox) {  
    73.             PPT.Shape shape = null;  
    74.             if (textBox == null || textBox.Location.IsEmpty || textBox.FrameSize.IsEmpty)  
    75.                 return shape;  
    76.             shape = shapes.AddTextbox(textBox.Orientation, textBox.X, textBox.Y, textBox.Width, textBox.Height);  
    77.             shape.TextFrame.HorizontalAnchor = textBox.HorizontalAnchor;  
    78.             shape.TextFrame.VerticalAnchor = textBox.VerticalAnchor;  
    79.             shape.TextFrame.TextRange.Font.Color.RGB = colorFormat(textBox.ForeColor);  
    80.             shape.TextFrame.TextRange.Font.Bold = textBox.Font.Bold ? MsoTriState.msoTrue : MsoTriState.msoFalse;  
    81.             shape.TextFrame.TextRange.Font.Italic = textBox.Font.Italic ? MsoTriState.msoTrue : MsoTriState.msoFalse;  
    82.             shape.TextFrame.TextRange.Font.Underline = textBox.Font.Underline ? MsoTriState.msoTrue : MsoTriState.msoFalse;  
    83.             shape.TextFrame.TextRange.Font.Size = textBox.Font.Size;  
    84.             shape.TextFrame.TextRange.Font.Name = textBox.Font.Name;  
    85.             shape.TextFrame.MarginLeft = 0;  
    86.             shape.TextFrame.MarginRight = 0;  
    87.             if (textBox.BackColor == Color.Transparent) {  
    88.                 shape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;  
    89.             } else {  
    90.                 shape.Fill.BackColor.RGB = colorFormat(textBox.BackColor);  
    91.             }  
    92.             shape.Line.Weight = textBox.BoardWeight;  
    93.             if (textBox.BoardColor == Color.Transparent) {  
    94.                 shape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;  
    95.             } else {  
    96.                 shape.Line.BackColor.RGB = colorFormat(textBox.BoardColor);  
    97.             }  
    98.             shape.Line.DashStyle = textBox.BoardStyle;  
    99.             shape.TextFrame.TextRange.Text = textBox.Text;  
    100.             return shape;  
    101.         }  
    102.         #endregion   
    103.   
    104.         #region 添加基本图形  
    105.         //画直线  
    106.         public PPT.Shape drawLine(PPT.Shapes shapes, float beginX, float beginY, float endX, float endY) {  
    107.             PPT.Shape shape = shapes.AddLine(beginX, beginY, endX, endY);  
    108.             return shape;  
    109.         }  
    110.         //画直线  
    111.         public PPT.Shape drawLine(PPT.Shapes shapes, float beginX, float beginY, float endX, float endY, float weight, Color foreColor) {  
    112.             PPT.Shape shape = shapes.AddLine(beginX, beginY, endX, endY);  
    113.             shape.Line.ForeColor.RGB = colorFormat(foreColor);  //线条颜色  
    114.             shape.Line.Weight = weight;                         //线条粗细  
    115.             return shape;  
    116.         }  
    117.         //画矩形  
    118.         public PPT.Shape drawRectangle(PPT.Shapes shapes, float beginX, float beginY, float width, float height) {  
    119.             PPT.Shape shape = shapes.AddShape(MsoAutoShapeType.msoShapeRectangle, beginX, beginY, width, height);  
    120.             return shape;  
    121.         }  
    122.         //画矩形  
    123.         public PPT.Shape drawRectangle(PPT.Shapes shapes, float beginX, float beginY, float width, float height, float weight, Color foreColor, Color backColor) {  
    124.             PPT.Shape shape = shapes.AddShape(MsoAutoShapeType.msoShapeRectangle, beginX, beginY, width, height);  
    125.             shape.Line.ForeColor.RGB = colorFormat(foreColor);  //线条颜色  
    126.             shape.Fill.BackColor.RGB = colorFormat(backColor);  //填充颜色  
    127.             shape.Line.Weight = weight;                         //线条粗细  
    128.             return shape;  
    129.         }  
    130.         //画箭头  
    131.         public PPT.Shape drawArrow(PPT.Shapes shapes, float beginX, float beginY, float endX, float endY,float weight) {  
    132.             float width=(float)Math.Sqrt(Math.Pow(endX-beginX,2)+Math.Pow(endY-beginY,2));  
    133.             float startX = (beginX + endX) / 2-width/2;  
    134.             float startY = (beginY + endY) / 2;  
    135.             float angle = endX==beginX?(endY>beginY?90:-90):(float)Math.Atan((endY - beginY) / (endX - beginX));  
    136.             angle = (float)(angle / Math.PI * 180.0);  
    137.             angle = angle < 0 ? 180.0f + angle : angle;  
    138.             PPT.Shape shape = shapes.AddShape(MsoAutoShapeType.msoShapeRightArrow, startX, startY, width, weight);  
    139.             shape.Rotation = angle;  
    140.             return shape;  
    141.         }  
    142.         //画箭头  
    143.         public PPT.Shape drawRightArrow(PPT.Shapes shapes, float beginX, float beginY, float endX, float endY, float weight, Color foreColor, Color backColor) {  
    144.             PPT.Shape shape = drawArrow(shapes, beginX, beginY, endX, endY, weight);  
    145.             shape.Line.ForeColor.RGB = colorFormat(foreColor);  //线条颜色  
    146.             shape.Fill.BackColor.RGB = colorFormat(backColor);  //填充颜色  
    147.             return shape;  
    148.         }  
    149.         #endregion  
    150.   
    151.         #region 添加图片  
    152.         public PPT.Shape AddPicture(PPT.Shapes shapes, string picPath, float beginX, float beginY, float width, float height) {  
    153.             PPT.Shape shape = null;  
    154.             if (!File.Exists(picPath)) {  
    155.                 throw new Exception("图片文件不存在!");  
    156.             } else {  
    157.                 shape = shapes.AddPicture(picPath, MsoTriState.msoFalse, MsoTriState.msoTrue, beginX, beginY, width, height);  
    158.             }  
    159.             return shape;  
    160.         }  
    161.         public PPT.Shape AddPicture(PPT.Shapes shapes, Bitmap bitmap, float beginX, float beginY, float width, float height) {  
    162.             PPT.Shape shape = null;  
    163.             string picPath=System.IO.Path.GetTempPath()+"bitmap.bmp";  
    164.             bitmap.Save(picPath, ImageFormat.Bmp);  
    165.             shape = shapes.AddPicture(picPath, MsoTriState.msoFalse, MsoTriState.msoTrue, beginX, beginY, width, height);  
    166.             return shape;  
    167.         }  
    168.         #endregion   
    169.    
    170.         public void Close() {  
    171.             try {  
    172.                 //WdSaveFormat为PPT文档的保存格式  
    173.                 PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;  
    174.                 //将pptDoc文档对象的内容保存为PPT文档  
    175.                 pptDoc.SaveAs(pptPath, format, Microsoft.Office.Core.MsoTriState.msoFalse);  
    176.    
    177.                 //关闭pptDoc文档对象  
    178.                 pptDoc.Close();  
    179.                 //关闭pptApp组件对象  
    180.                 pptApp.Quit();  
    181.             } catch (Exception ex) {  
    182.                 outPrint.appendText("保存或关闭PPT出错,错误信息:" + ex.Message);  
    183.             }  
    184.         }  
    185.         /// <summary>  
    186.         /// 系统颜色转换为PPT支持的颜色值  
    187.         /// </summary>  
    188.         private int colorFormat(System.Drawing.Color color) {  
    189.             int value = ((color.B * 256 + color.G) * 256) + color.R;//Office RGB与 System.Drawing.Color.RGB顺序相反  
    190.             return value;  
    191.         }  
    192.     }  
    193. }  
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using OFFICECORE = Microsoft.Office.Core;
    using POWERPOINT = Microsoft.Office.Interop.PowerPoint;
    using System.Windows;
    using System.Collections;
    using System.Windows.Controls;
    namespace PPTDraw.PPTOperate
    {
      /// <summary>
      /// PPT文档操作实现类.
      /// </summary>
      public class OperatePPT
      {
        #region=========基本的参数信息=======
        POWERPOINT.Application objApp = null;
        POWERPOINT.Presentation objPresSet = null;
        POWERPOINT.SlideShowWindows objSSWs;
        POWERPOINT.SlideShowTransition objSST;
        POWERPOINT.SlideShowSettings objSSS;
        POWERPOINT.SlideRange objSldRng;
        bool bAssistantOn;
        double pixperPoint = 0;
        double offsetx = 0;
        double offsety = 0;
        #endregion
        #region===========操作方法==============
        /// <summary>
        /// 打开PPT文档并播放显示。
        /// </summary>
        /// <param name="filePath">PPT文件路径</param>
        public void PPTOpen(string filePath)
        {
          //防止连续打开多个PPT程序.
          if (this.objApp != null) { return; }
          try
          {
            objApp = new POWERPOINT.Application();
            //以非只读方式打开,方便操作结束后保存.
            objPresSet = objApp.Presentations.Open(filePath, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse);
            //Prevent Office Assistant from displaying alert messages:
            bAssistantOn = objApp.Assistant.On;
            objApp.Assistant.On = false;
            objSSS = this.objPresSet.SlideShowSettings;
            objSSS.Run();
          }
          catch (Exception ex)
          {
            this.objApp.Quit();
          }
        }
        /// <summary>
        /// 自动播放PPT文档.
        /// </summary>
        /// <param name="filePath">PPTy文件路径.</param>
        /// <param name="playTime">翻页的时间间隔.【以秒为单位】</param>
        public void PPTAuto(string filePath, int playTime)
        {
          //防止连续打开多个PPT程序.
          if (this.objApp != null) { return; }
          objApp = new POWERPOINT.Application();
          objPresSet = objApp.Presentations.Open(filePath, OFFICECORE.MsoTriState.msoCTrue, OFFICECORE.MsoTriState.msoFalse, OFFICECORE.MsoTriState.msoFalse);
          // 自动播放的代码(开始)
          int Slides = objPresSet.Slides.Count;
          int[] SlideIdx = new int[Slides];
          for (int i = 0; i < Slides; i++) { SlideIdx[i] = i + 1; };
          objSldRng = objPresSet.Slides.Range(SlideIdx);
          objSST = objSldRng.SlideShowTransition;
          //设置翻页的时间.
          objSST.AdvanceOnTime = OFFICECORE.MsoTriState.msoCTrue;
          objSST.AdvanceTime = playTime;
          //翻页时的特效!
          objSST.EntryEffect = POWERPOINT.PpEntryEffect.ppEffectCircleOut;
          //Prevent Office Assistant from displaying alert messages:
          bAssistantOn = objApp.Assistant.On;
          objApp.Assistant.On = false;
          //Run the Slide show from slides 1 thru 3.
          objSSS = objPresSet.SlideShowSettings;
          objSSS.StartingSlide = 1;
          objSSS.EndingSlide = Slides;
          objSSS.Run();
          //Wait for the slide show to end.
          objSSWs = objApp.SlideShowWindows;
          while (objSSWs.Count >= 1) System.Threading.Thread.Sleep(playTime * 100);
          this.objPresSet.Close();
          this.objApp.Quit();
        }
        /// <summary>
        /// PPT下一页。
        /// </summary>
        public void NextSlide()
        {
          if (this.objApp != null)
            this.objPresSet.SlideShowWindow.View.Next();
        }
        /// <summary>
        /// PPT上一页。
        /// </summary>
        public void PreviousSlide()
        {
          if (this.objApp != null)
            this.objPresSet.SlideShowWindow.View.Previous();
        }
        /// <summary>
        /// 对当前的PPT页面进行图片插入操作。
        /// </summary>
        /// <param name="alImage">图片对象信息数组</param>
        /// <param name="offsetx">插入图片距离左边长度</param>
        /// <param name="pixperPoint">距离比例值</param>
        /// <returns>是否添加成功!</returns>
        public bool InsertToSlide(List<PPTOBJ> listObj)
        {
          bool InsertSlide = false;
          if (this.objPresSet != null)
          {
            this.SlideParams();
            int slipeint = objPresSet.SlideShowWindow.View.CurrentShowPosition;
            foreach (PPTOBJ myobj in listObj)
            {
              objPresSet.Slides[slipeint].Shapes.AddPicture(
                 myobj.Path,      //图片路径
                 OFFICECORE.MsoTriState.msoFalse,
                 OFFICECORE.MsoTriState.msoTrue,
                 (float)((myobj.X - this.offsetx) / this.pixperPoint),    //插入图片距离左边长度
                 (float)(myobj.Y / this.pixperPoint),    //插入图片距离顶部高度
                 (float)(myobj.Width / this.pixperPoint),  //插入图片的宽度
                 (float)(myobj.Height / this.pixperPoint)  //插入图片的高度
               );
            }
            InsertSlide = true;
          }
          return InsertSlide;
        }
        /// <summary>
        /// 计算InkCanvas画板上的偏移参数,与PPT上显示图片的参数。
        /// 用于PPT加载图片时使用
        /// </summary>
        private void SlideParams()
        {
          double slideWidth = this.objPresSet.PageSetup.SlideWidth;
          double slideHeight = this.objPresSet.PageSetup.SlideHeight;
          double inkCanWidth = SystemParameters.PrimaryScreenWidth;//inkCan.ActualWidth;
          double inkCanHeight = SystemParameters.PrimaryScreenHeight;//inkCan.ActualHeight ;
          if ((slideWidth / slideHeight) > (inkCanWidth / inkCanHeight))
          {
            this.pixperPoint = inkCanHeight / slideHeight;
            this.offsetx = 0;
            this.offsety = (inkCanHeight - slideHeight * this.pixperPoint) / 2;
          }
          else
          {
            this.pixperPoint = inkCanHeight / slideHeight;
            this.offsety = 0;
            this.offsetx = (inkCanWidth - slideWidth * this.pixperPoint) / 2;
          }
        }
        /// <summary>
        /// 关闭PPT文档。
        /// </summary>
        public void PPTClose()
        {
          //装备PPT程序。
          if (this.objPresSet != null)
          {
            //判断是否退出程序,可以不使用。
            //objSSWs = objApp.SlideShowWindows;
            //if (objSSWs.Count >= 1)
            //{
              if (MessageBox.Show("是否保存修改的笔迹!", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                this.objPresSet.Save();
            //}
            //this.objPresSet.Close();
          }
          if (this.objApp != null)
            this.objApp.Quit();
          GC.Collect();
        }
        #endregion
      }
    }
    

     主要实现将ppt转换成html的功能,方法很多

    using System;
     using System.Collections.Generic;
     using System.Text;
     using System.IO;
     using PPT = Microsoft.Office.Interop.PowerPoint;
     using System.Reflection;
     
    namespace WritePptDemo
     {
       class Program
       {
         static void Main(string[] args)
         {
           string  path;     //文件路径变量
     
           PPT.Application pptApp;   //PPT应用程序变量
            PPT.Presentation pptDoc;   //PPT文档变量
     
           PPT.Presentation pptDoctmp;
     
          path  = @"C:MyPPT.ppt";   //路径
           pptApp =  new PPT.ApplicationClass();  //初始化
     
          //如果已存在,则删除
           if  (File.Exists((string)path))
           {
              File.Delete((string)path);
           }
     
          //由于使用的是COM库,因此有许多变量需要用Nothing代替
           Object  Nothing = Missing.Value;
           pptDoc =  pptApp.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoc.Slides.Add(1,  Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText);
     
           string text = "示例文本";
     
          foreach  (PPT.Slide slide in pptDoc.Slides)
           {
              foreach (PPT.Shape shape in slide.Shapes)
              {
                shape.TextFrame.TextRange.InsertAfter(text);
              }
           }
     
            //WdSaveFormat为Excel文档的保存格式
            PPT.PpSaveAsFileType format = PPT.PpSaveAsFileType.ppSaveAsDefault;
     
          //将excelDoc文档对象的内容保存为XLSX文档 
            pptDoc.SaveAs(path, format, Microsoft.Office.Core.MsoTriState.msoFalse);
     
          //关闭excelDoc文档对象 
            pptDoc.Close();
     
          //关闭excelApp组件对象 
            pptApp.Quit();
     
           Console.WriteLine(path + " 创建完毕!");
     
           Console.ReadLine();
     
     
           string  pathHtml = @"c:MyPPT.html";
     
           PPT.Application pa = new PPT.ApplicationClass();
     
           pptDoctmp = pa.Presentations.Open(path,  Microsoft.Office.Core.MsoTriState.msoTrue,  Microsoft.Office.Core.MsoTriState.msoFalse,  Microsoft.Office.Core.MsoTriState.msoFalse);
            PPT.PpSaveAsFileType formatTmp = PPT.PpSaveAsFileType.ppSaveAsHTML;
            pptDoctmp.SaveAs(pathHtml, formatTmp,  Microsoft.Office.Core.MsoTriState.msoFalse);
            pptDoctmp.Close();
           pa.Quit();
            Console.WriteLine(pathHtml + " 创建完毕!");
         }
       }
     }
    

      

     

  • 相关阅读:
    (转)使用 PyInstaller 把python程序 .py转为 .exe 可执行程序
    (转)使用 python Matplotlib 库绘图
    使用Matplotlib画图系列(一)
    Numpy常用金融计算(一)
    Windows中安装Linux子系统的详细步骤
    Centos7+Postfix+Dovecot实现内网邮件收发 风行天下
    centos7系统防火墙端口转发 风行天下
    Centos7+Postfix+Dovecot实现内网邮件收发
    centos7的路径含有空格Linux命令使用时路径存在空格、特殊符号(如、@等等) 风行天下
    zabbix无法使用Detect operating system [zabbix] 风行天下
  • 原文地址:https://www.cnblogs.com/gisoracle/p/6060595.html
Copyright © 2011-2022 走看看