簡體   English   中英

使用C#提取PowerPoint標題

[英]Extract powerpoint titles with C#

我有powerponint 97-2003文件(擴展名為.ppt),我需要以編程方式使用C#提取幻燈片標題。 我嘗試使用Microsoft.Office.Interop,但沒有成功。 我用google搜索,最大程度地找到了如何獲得對PowerPoint.Slide的引用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;

namespace Tester
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.PowerPoint.Application presentationApp = new Microsoft.Office.Interop.PowerPoint.Application();

            try
            {
                string pptPath = @"D:\somefile.ppt";
                TestReadingTitles(presentationApp, pptPath);
            }
            finally
            {
                presentationApp.Quit();
            }
        }

        private static void TestReadingTitles(Microsoft.Office.Interop.PowerPoint.Application presentationApp, string pptPath)
        {
            presentationApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
            Microsoft.Office.Interop.PowerPoint.Presentations presentations = presentationApp.Presentations;

            Microsoft.Office.Core.MsoTriState readOnly = Microsoft.Office.Core.MsoTriState.msoTrue;
            Microsoft.Office.Core.MsoTriState untitled = Microsoft.Office.Core.MsoTriState.msoTrue;
            Microsoft.Office.Core.MsoTriState withWindow = Microsoft.Office.Core.MsoTriState.msoFalse;

            Microsoft.Office.Interop.PowerPoint.Presentation presentation = presentations.Open(pptPath, readOnly, untitled, withWindow);
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                foreach (PowerPoint.Slide slide in presentation.Slides)
                {
                    string slidetitle = ??????????????????;
                }
            }

        }


    }
}

您可以提取標題而無需遍歷形狀。

    private static string ExtractSlideTitlefromSlide(Microsoft.Office.Interop.PowerPoint.Slide slide, string defaultValue)
    {
        if (slide.Shapes.HasTitle == Office.MsoTriState.msoTrue)
        {
            if (slide.Shapes.Title.TextFrame.HasText == Office.MsoTriState.msoTrue)
            {
                return slide.Shapes.Title.TextFrame.TextRange.Text;
            }
        }

        return defaultValue;
    }

我沒有直接從ppt提取幻燈片標題的解決方案。 這是一個工作環境-首先臨時將其轉換為pptx,然后使用openxml提取標題。 對於從ppt到pptx的轉換,我使用了我不喜歡的Microsoft Interop,但是我沒有更好的解決方案。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using D = DocumentFormat.OpenXml.Drawing;
using Shape = DocumentFormat.OpenXml.Presentation.Shape; 

namespace Tester
{
    class Program
    {
        static void Main(string[] args)
        {
            string pptPath = @"D:\mypresentation.ppt";
            ReadTitles(pptPath);
        }

        private static void ReadTitles(string pptPath)
        {
            IList<string> slideTitles = GetSlidesTitles(pptPath);
            Debug.Print("SLIDES TITLES FOR {0}:", pptPath);
            foreach (string slideTitle in slideTitles)
            {
                Debug.Print("\t {0}", slideTitle);
            }
        }

        private static IList<string> GetSlidesTitles(string pptPath)
        {
            string pptxPath = SaveAsPptx(pptPath);
            IList<string> titles = GetSlideTitles(pptxPath);
            try
            {
                File.Delete(pptxPath);
                Debug.Print("Temporary pptx file {0} deleted.", pptxPath);
            }
            catch (Exception e)
            {
                Debug.Print("Error deleting file {0}. ERROR: {1}", pptxPath, e.Message);
            }
            return titles;
        }

        private static string SaveAsPptx(string pptPathIn)
        {

            Microsoft.Office.Interop.PowerPoint.Application presentationApp = new Microsoft.Office.Interop.PowerPoint.Application();
            string pptxPathOut = null;
            try
            {

                string pptDir = Path.GetDirectoryName(pptPathIn);
                string pptFileNameOnly = Path.GetFileNameWithoutExtension(pptPathIn);
                pptxPathOut = Path.Combine(pptDir, pptFileNameOnly + ".pptx");
                presentationApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;

                Microsoft.Office.Interop.PowerPoint.Presentations presentations = presentationApp.Presentations;

                Microsoft.Office.Core.MsoTriState readOnly = Microsoft.Office.Core.MsoTriState.msoFalse;
                Microsoft.Office.Core.MsoTriState untitled = Microsoft.Office.Core.MsoTriState.msoFalse;
                Microsoft.Office.Core.MsoTriState withWindow = Microsoft.Office.Core.MsoTriState.msoFalse;

                Debug.Print("Opening ppt file {0} ...", pptPathIn);
                Microsoft.Office.Interop.PowerPoint.Presentation presentation = presentations.Open(pptPathIn, readOnly, untitled, withWindow);

                Debug.Print("Starting creation of pptx from ppt {0}", pptPathIn);
                presentation.SaveCopyAs(pptxPathOut, PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation, Microsoft.Office.Core.MsoTriState.msoFalse);
                Debug.Print("Successfully created pptx {0} from ppt {1}", pptxPathOut, pptPathIn);
            }
            catch (Exception e)
            {
                Debug.Print("Error during creating pptx from ppt " + pptPathIn, e);
            }
            finally
            {
                presentationApp.Quit();
            }

            return pptxPathOut;
        }


        // Get a list of the titles of all the slides in the presentation.
        public static IList<string> GetSlideTitles(string presentationFile)
        {
            // Open the presentation as read-only.
            using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false))
            {
                return GetSlideTitles(presentationDocument);
            }
        }

        // Get a list of the titles of all the slides in the presentation.
        public static IList<string> GetSlideTitles(PresentationDocument presentationDocument)
        {
            if (presentationDocument == null)
            {
                throw new ArgumentNullException("presentationDocument");
            }

            // Get a PresentationPart object from the PresentationDocument object.
            PresentationPart presentationPart = presentationDocument.PresentationPart;

            if (presentationPart != null &&
                presentationPart.Presentation != null)
            {
                // Get a Presentation object from the PresentationPart object.
                Presentation presentation = presentationPart.Presentation;

                if (presentation.SlideIdList != null)
                {
                    List<string> titlesList = new List<string>();

                    // Get the title of each slide in the slide order.
                    foreach (var slideId in presentation.SlideIdList.Elements<SlideId>())
                    {
                        SlidePart slidePart = presentationPart.GetPartById(slideId.RelationshipId) as SlidePart;

                        // Get the slide title.
                        string title = GetSlideTitle(slidePart);

                        // An empty title can also be added.
                        titlesList.Add(title);
                    }

                    return titlesList;
                }

            }

            return null;
        }

        // Get the title string of the slide.
        public static string GetSlideTitle(SlidePart slidePart)
        {
            if (slidePart == null)
            {
                throw new ArgumentNullException("slidePart");
            }

            // Declare a paragraph separator.
            string paragraphSeparator = null;

            if (slidePart.Slide != null)
            {
                // Find all the title shapes.
                var shapes = from shape in slidePart.Slide.Descendants<Shape>()
                             where IsTitleShape(shape)
                             select shape;

                StringBuilder paragraphText = new StringBuilder();

                foreach (var shape in shapes)
                {
                    // Get the text in each paragraph in this shape.
                    foreach (var paragraph in shape.TextBody.Descendants<D.Paragraph>())
                    {
                        // Add a line break.
                        paragraphText.Append(paragraphSeparator);

                        foreach (var text in paragraph.Descendants<D.Text>())
                        {
                            paragraphText.Append(text.Text);
                        }

                        paragraphSeparator = "\n";
                    }
                }

                return paragraphText.ToString();
            }

            return string.Empty;
        }

        // Determines whether the shape is a title shape.
        private static bool IsTitleShape(Shape shape)
        {
            var placeholderShape = shape.NonVisualShapeProperties.ApplicationNonVisualDrawingProperties.GetFirstChild<PlaceholderShape>();
            if (placeholderShape != null && placeholderShape.Type != null && placeholderShape.Type.HasValue)
            {
                switch ((PlaceholderValues)placeholderShape.Type)
                {
                    // Any title shape.
                    case PlaceholderValues.Title:

                    // A centered title.
                    case PlaceholderValues.CenteredTitle:
                        return true;

                    default:
                        return false;
                }
            }
            return false;
        }

    }
}

最終,我找到了一種方法,可以將.ppt文件中的PowerPoint演示文稿標題轉換為.pptx。 這是一個解決方案:

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

namespace Mintra.Publisher.DocumentConverter.Core.Utils
{
    class InteropUtility
    {


        public static IList<string> GetPresentationTitles(string pptPath)
        {

            IList<string> result = new List<string>();

            var presentationApp = new Microsoft.Office.Interop.PowerPoint.Application();

            try
            {
                presentationApp.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
                Microsoft.Office.Interop.PowerPoint.Presentations presentations = presentationApp.Presentations;

                var readOnly = Microsoft.Office.Core.MsoTriState.msoTrue;
                var untitled = Microsoft.Office.Core.MsoTriState.msoTrue;
                var withWindow = Microsoft.Office.Core.MsoTriState.msoFalse;

                Microsoft.Office.Interop.PowerPoint.Presentation presentation = presentations.Open(pptPath, readOnly, untitled, withWindow);
                int i = 0;
                foreach (PowerPoint.Slide slide in presentation.Slides)
                {
                    string defaultTitle = String.Format("Slide {0}", i);
                    String shapeTitle = ExtractSlideTitlefromShape(slide, defaultTitle);
                    result.Add(shapeTitle);
                }
            }
            finally
            {
                presentationApp.Quit();
            }


            return result;

        }

        private static string ExtractSlideTitlefromShape(PowerPoint.Slide slide, string defaultValue)
        {
            PowerPoint.HeadersFooters headersFooters = slide.HeadersFooters;
            PowerPoint.Shapes mastershapes = slide.Master.Shapes;

            for (int i = 1; i <= slide.Shapes.Count; i++)
            {
                PowerPoint.Shape shape = slide.Shapes[i];
                bool hasTextFrame = shape.HasTextFrame == MsoTriState.msoTrue;
                bool isTypePlaceholder = shape.Type.Equals(MsoShapeType.msoPlaceholder);
                bool hasTextInTextFrame = shape.TextFrame.HasText == MsoTriState.msoTrue;
                bool isTitleShape = shape.Name.ToLower().Contains("title");

                if (isTypePlaceholder && hasTextFrame && hasTextInTextFrame && isTitleShape)
                {
                    return shape.TextFrame.TextRange.Text;

                }
            }

            return defaultValue;
        }

    }
}
Microsoft.Office.Interop.PowerPoint.Application pptApplication = new Microsoft.Office.Interop.PowerPoint.Application();

            Microsoft.Office.Interop.PowerPoint.Slides slides;
            Microsoft.Office.Interop.PowerPoint._Slide slide;


            // Create the Presentation File
            Presentation pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoTrue);
            for (int i = 0; i < 2; i++)
            {
                Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutChartAndText];
               // customLayout.t

                // Create new Slide
                slides = pptPresentation.Slides;
                slide = slides.AddSlide(1, customLayout);
                slide.Shapes.Title.Top = 0;
                slide.Shapes.Title.TextFrame.TextRange.Text = "Welcome!";

您所需要做的就是更改歡迎文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM