Share via


Anleitung: Abrufen des gesamten Texts einer Folie in einer Präsentation

Letzte Änderung: Donnerstag, 14. Oktober 2010

Gilt für: Excel 2010 | Office 2010 | PowerPoint 2010 | Word 2010

Inhalt dieses Artikels
Abrufen eines PresentationDocument-Objekts
Grundlegende Präsentationsdokumentstruktur
Funktionsweise des Beispielcodes
Beispielcode

In diesem Thema wird erklärt, wie Sie mithilfe der Klassen im Open XML SDK 2.0 für Microsoft Office programmgesteuert den gesamten Text auf einer Folie in einer Präsentation abrufen können.

Die folgenden Assemblydirektiven sind zum Kompilieren des Codes in diesem Thema erforderlich.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Packaging;
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports DocumentFormat.OpenXml.Presentation
Imports DocumentFormat.OpenXml.Packaging

Abrufen eines PresentationDocument-Objekts

Im Open XML SDK stellt die PresentationDocument-Klasse ein Präsentationsdokumentpaket dar. Zum Arbeiten mit einem Präsentationsdokument müssen Sie zuerst eine Instanz der PresentationDocument-Klasse erstellen und anschließend mit dieser Instanz arbeiten. Rufen Sie zum Erstellen der Klasseninstanz anhand des Dokuments die PresentationDocument.Open(String, Boolean)-Methode auf, die einen Dateipfad und als zweiten Parameter einen booleschen Wert verwendet, um anzugeben, dass ein Dokument bearbeitbar ist. Zum Öffnen eines Dokuments mit Lese-/Schreibzugriff weisen Sie diesem Parameter den Wert true zu, zum Öffnen des Dokuments mit Schreibschutz weisen Sie den Wert false wie in der folgenden using-Anweisung gezeigt zu. In diesem Code ist der file-Parameter eine Zeichenfolge, die den Pfad der Datei darstellt, in dem Sie das Dokument öffnen möchten.

// Open the presentation as read-only.
    using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false))
{
    // Insert other code here.
}
Using presentationDocument As PresentationDocument = PresentationDocument.Open(file, False)
    ' Insert other code here.
End Using

Die using-Anweisung ist eine empfohlene Alternative zur herkömmlichen Reihenfolge ".Open, .Save, .Close". Sie stellt sicher, dass die Dispose-Methode (vom Open XML SDK verwendete interne Methode zum Bereinigen von Ressourcen) bei Erreichen der schließenden Klammer automatisch aufgerufen wird. Der auf die using-Anweisung folgende Block richtet einen Bereich für das Objekt ein, das in der using-Anweisung erstellt oder benannt wird, in diesem Fall presentationDocument.

Grundlegende Präsentationsdokumentstruktur

Die grundlegende Dokumentstruktur eines PresentationML-Dokuments besteht aus dem Hauptteil, der die Präsentationsdefinition enthält. Im folgenden Text aus der Spezifikation ISO/IEC 29500 wird die Gesamtstruktur eines PresentationML-Pakets eingeführt.

Der Hauptteil eines PresentationML-Pakets beginnt mit dem Stammelement der Präsentation. Dieses Element enthält eine Präsentation, die wiederum auf eine Folienliste, eine Folienmasterliste, eine Notizenmasterliste und eine Handzettelmaster-Liste verweist. Die Folienliste verweist auf alle Folien in der Präsentation. Die Folienmasterliste verweist auf sämtliche in der Präsentation verwendeten Folienmaster. Der Notizenmaster enthält Informationen zur Formatierung der Notizenseiten. Der Handzettelmaster beschreibt das Aussehen eines Handzettels.

Ein Handzettel ist ein gedruckter Foliensatz, der an das Publikum zur späteren Bezugnahme verteilt werden kann.

Neben Text und Grafiken kann jede Folie Kommentare und Notizen enthalten, ein Layout aufweisen und Teil mindestens einer zielgruppenorientierten Präsentation sein. (Ein Kommentar ist eine an die Person, die die Präsentationsfolien verwaltet, gerichtete Anmerkung. Eine Notiz ist eine Erinnerung oder eine kurze Textstelle, die für den Präsentator oder das Publikum bestimmt ist.)

Andere Features, die ein PresentationML-Dokument enthalten kann, sind Animationen, Audio, Video und Übergänge zwischen den Folien.

Ein PresentationML-Dokument wird nicht als ein großer Textkörper in einem einzelnen Teil gespeichert. Die Elemente, mit deren Hilfe bestimmte Funktionsgruppierungen erfolgen, sind stattdessen in mehreren Teilen gespeichert. Beispielsweise sind alle Kommentare in einem Dokument in einem Kommentarteil gespeichert, wobei jede Folie über einen eigenen Teil verfügt.

© ISO/IEC29500: 2008.

Das folgende XML-Codesegment stellt eine Präsentation dar, die zwei Folien mit den IDs 267 und 256 enthält.

<p:presentation xmlns:p="…" … > 
   <p:sldMasterIdLst>
      <p:sldMasterId
         xmlns:rel="http://…/relationships" rel:id="rId1"/>
   </p:sldMasterIdLst>
   <p:notesMasterIdLst>
      <p:notesMasterId
         xmlns:rel="http://…/relationships" rel:id="rId4"/>
   </p:notesMasterIdLst>
   <p:handoutMasterIdLst>
      <p:handoutMasterId
         xmlns:rel="http://…/relationships" rel:id="rId5"/>
   </p:handoutMasterIdLst>
   <p:sldIdLst>
      <p:sldId id="267"
         xmlns:rel="http://…/relationships" rel:id="rId2"/>
      <p:sldId id="256"
         xmlns:rel="http://…/relationships" rel:id="rId3"/>
   </p:sldIdLst>
       <p:sldSz cx="9144000" cy="6858000"/>
   <p:notesSz cx="6858000" cy="9144000"/>
</p:presentation>

Mithilfe des Open XML SDK 2.0 können Sie eine Dokumentstruktur und Inhalte erstellen, indem Sie stark typisierte Klassen verwenden, die PresentationML-Elementen entsprechen. Diese Klassen sind im DocumentFormat.OpenXml.Presentation-Namespace enthalten. Die folgende Tabelle enthält die Namen der Klassen, die den Elementen sld, sldLayout, sldMaster und notesMaster entsprechen.

PresentationML-Element

Open XML SDK 2.0-Klasse

Beschreibung

sld

Slide

Präsentationsfolie. Das SlidePart-Stammelement.

sldLayout

SlideLayout

Das Folienlayout. Das SlideLayoutPart-Stammelement.

sldMaster

SlideMaster

Der Folienmaster. Das SlideMasterPart-Stammelement.

notesMaster

NotesMaster

Notizenmaster (oder Handzettelmaster). Das NotesMasterPart-Stammelement.

Funktionsweise des Beispielcodes

Der Beispielcode besteht aus drei Überladungen der GetAllTextInSlide-Methode. Im folgenden Segment öffnet die erste überladene Methode die Quellpräsentation, die die Folie mit dem abzurufenden Text enthält, und übergibt die Präsentation an die zweite überladene Methode, die den Folienteil abruft. Diese Methode gibt das Array von Zeichenfolgen zurück, das die zweite Methode an sie zurückgibt, von denen jede einen Textabsatz auf der angegebenen Folie darstellt.

// Get all the text in a slide.
public static string[] GetAllTextInSlide(string presentationFile, int slideIndex)
{
    // Open the presentation as read-only.
    using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false))
    {
        // Pass the presentation and the slide index
        // to the next GetAllTextInSlide method, and
        // then return the array of strings it returns. 
        return GetAllTextInSlide(presentationDocument, slideIndex);
    }
}
' Get all the text in a slide.
Public Shared Function GetAllTextInSlide(ByVal presentationFile As String, ByVal slideIndex As Integer) As String()
    ' Open the presentation as read-only.
    Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, False)
        ' Pass the presentation and the slide index
        ' to the next GetAllTextInSlide method, and
        ' then return the array of strings it returns. 
        Return GetAllTextInSlide(presentationDocument, slideIndex)
    End Using
End Function

Die zweite überladene Methode verwendet das übergebene Präsentationsdokument und ruft einen Folienteil ab, der an die dritte überladene Methode übergeben wird. Sie gibt an die erste überladene Methode das Array von Zeichenfolgen zurück, das die dritte überladene Methode an sie zurückgibt, von denen jede einen Textabsatz auf der angegebenen Folie darstellt.

public static string[] GetAllTextInSlide(PresentationDocument presentationDocument, int slideIndex)
{
    // Verify that the presentation document exists.
    if (presentationDocument == null)
    {
        throw new ArgumentNullException("presentationDocument");
    }

    // Verify that the slide index is not out of range.
    if (slideIndex < 0)
    {
        throw new ArgumentOutOfRangeException("slideIndex");
    }

    // Get the presentation part of the presentation document.
    PresentationPart presentationPart = presentationDocument.PresentationPart;

    // Verify that the presentation part and presentation exist.
    if (presentationPart != null && presentationPart.Presentation != null)
    {
        // Get the Presentation object from the presentation part.
        Presentation presentation = presentationPart.Presentation;

        // Verify that the slide ID list exists.
        if (presentation.SlideIdList != null)
        {
            // Get the collection of slide IDs from the slide ID list.
            var slideIds = presentation.SlideIdList.ChildElements;

            // If the slide ID is in range...
            if (slideIndex < slideIds.Count)
            {
                // Get the relationship ID of the slide.
                string slidePartRelationshipId = (slideIds[slideIndex] as SlideId).RelationshipId;

                // Get the specified slide part from the relationship ID.
                SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId);

                // Pass the slide part to the next method, and
                // then return the array of strings that method
                // returns to the previous method.
                return GetAllTextInSlide(slidePart);
            }
        }
    }
    // Else, return null.
    return null;
}
Public Shared Function GetAllTextInSlide(ByVal presentationDocument As PresentationDocument, ByVal slideIndex As Integer) As String()
    ' Verify that the presentation document exists.
    If presentationDocument Is Nothing Then
        Throw New ArgumentNullException("presentationDocument")
    End If

    ' Verify that the slide index is not out of range.
    If slideIndex < 0 Then
        Throw New ArgumentOutOfRangeException("slideIndex")
    End If

    ' Get the presentation part of the presentation document.
    Dim presentationPart As PresentationPart = presentationDocument.PresentationPart

    ' Verify that the presentation part and presentation exist.
    If presentationPart IsNot Nothing AndAlso presentationPart.Presentation IsNot Nothing Then
        ' Get the Presentation object from the presentation part.
        Dim presentation As Presentation = presentationPart.Presentation

        ' Verify that the slide ID list exists.
        If presentation.SlideIdList IsNot Nothing Then
            ' Get the collection of slide IDs from the slide ID list.
            Dim slideIds = presentation.SlideIdList.ChildElements

            ' If the slide ID is in range...
            If slideIndex < slideIds.Count Then
                ' Get the relationship ID of the slide.
                Dim slidePartRelationshipId As String = (TryCast(slideIds(slideIndex), SlideId)).RelationshipId

                ' Get the specified slide part from the relationship ID.
                Dim slidePart As SlidePart = CType(presentationPart.GetPartById(slidePartRelationshipId), SlidePart)

                ' Pass the slide part to the next method, and
                ' then return the array of strings that method
                ' returns to the previous method.
                Return GetAllTextInSlide(slidePart)
            End If
        End If
    End If

    ' Else, return null.
    Return Nothing
End Function

Das folgende Codesegment zeigt die dritte überladene Methode, die den übergebenen Folienteil übernimmt und an die zweite überladene Methode ein Zeichenfolgenarray mit Textabsätzen zurückgibt. Zunächst überprüft die Methode, ob der übergebene Folienteil vorhanden ist, und erstellt eine verknüpfte Liste mit Zeichenfolgen. Sie durchläuft die Absätze der übergebenen Folie, verkettet alle Textzeilen in einem Absatz mithilfe eines StringBuilder-Objekts und weist jeden Absatz einer Zeichenfolge in der verknüpften Liste zu. Dann gibt sie an die zweite überladene Methode ein Zeichenfolgenarray zurück, das den gesamten Text auf der angegebenen Folie in der Präsentation darstellt.

public static string[] GetAllTextInSlide(SlidePart slidePart)
{
    // Verify that the slide part exists.
    if (slidePart == null)
    {
        throw new ArgumentNullException("slidePart");
    }

    // Create a new linked list of strings.
    LinkedList<string> texts = new LinkedList<string>();

    // If the slide exists...
    if (slidePart.Slide != null)
    {
        // Iterate through all the paragraphs in the slide.
        foreach (var paragraph in slidePart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Paragraph>())
        {
            // Create a new string builder.                    
            StringBuilder paragraphText = new StringBuilder();

            // Iterate through the lines of the paragraph.
            foreach (var text in paragraph.Descendants<DocumentFormat.OpenXml.Drawing.Text>())
            {
                // Append each line to the previous lines.
                paragraphText.Append(text.Text);
            }

            if (paragraphText.Length > 0)
            {
                // Add each paragraph to the linked list.
                texts.AddLast(paragraphText.ToString());
            }
        }
    }

    if (texts.Count > 0)
    {
        // Return an array of strings.
        return texts.ToArray();
    }
    else
    {
        return null;
    }
}
Public Shared Function GetAllTextInSlide(ByVal slidePart As SlidePart) As String()
    ' Verify that the slide part exists.
    If slidePart Is Nothing Then
        Throw New ArgumentNullException("slidePart")
    End If

    ' Create a new linked list of strings.
    Dim texts As New LinkedList(Of String)()

    ' If the slide exists...
    If slidePart.Slide IsNot Nothing Then
        ' Iterate through all the paragraphs in the slide.
        For Each paragraph In slidePart.Slide.Descendants(Of DocumentFormat.OpenXml.Drawing.Paragraph)()
            ' Create a new string builder.                    
            Dim paragraphText As New StringBuilder()

            ' Iterate through the lines of the paragraph.
            For Each text In paragraph.Descendants(Of DocumentFormat.OpenXml.Drawing.Text)()
                ' Append each line to the previous lines.
                paragraphText.Append(text.Text)
            Next text

            If paragraphText.Length > 0 Then
                ' Add each paragraph to the linked list.
                texts.AddLast(paragraphText.ToString())
            End If
        Next paragraph
    End If

    If texts.Count > 0 Then
        ' Return an array of strings.
        Return texts.ToArray()
    Else
        Return Nothing
    End If
End Function

Beispielcode

Nachstehend ist der vollständige Beispielcode aufgeführt, mit dem Sie den gesamten Text auf einer bestimmten Folie in einer Präsentationsdatei abrufen können. Sie können beispielsweise die folgende foreach-Schleife in einem Programm verwenden, um das von der GetAllTextInSlide-Methode zurückgegebene Zeichenfolgenarray abzurufen, das den Text auf der zweiten Folie in der Präsentationsdatei "Myppt8.pptx" darstellt.

foreach (string s in GetAllTextInSlide(@"C:\Users\Public\Documents\Myppt8.pptx", 1))
    Console.WriteLine(s);
For Each s As String In GetAllTextInSlide("C:\Users\Public\Documents\Myppt8.pptx", 1)
    Console.WriteLine(s)
Next

Nachstehend ist der vollständige Beispielcode in C# und Visual Basic aufgeführt.

// Get all the text in a slide.
public static string[] GetAllTextInSlide(string presentationFile, int slideIndex)
{
    // Open the presentation as read-only.
    using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, false))
    {
        // Pass the presentation and the slide index
        // to the next GetAllTextInSlide method, and
        // then return the array of strings it returns. 
        return GetAllTextInSlide(presentationDocument, slideIndex);
    }
}
public static string[] GetAllTextInSlide(PresentationDocument presentationDocument, int slideIndex)
{
    // Verify that the presentation document exists.
    if (presentationDocument == null)
    {
        throw new ArgumentNullException("presentationDocument");
    }

    // Verify that the slide index is not out of range.
    if (slideIndex < 0)
    {
        throw new ArgumentOutOfRangeException("slideIndex");
    }

    // Get the presentation part of the presentation document.
    PresentationPart presentationPart = presentationDocument.PresentationPart;

    // Verify that the presentation part and presentation exist.
    if (presentationPart != null && presentationPart.Presentation != null)
    {
        // Get the Presentation object from the presentation part.
        Presentation presentation = presentationPart.Presentation;

        // Verify that the slide ID list exists.
        if (presentation.SlideIdList != null)
        {
            // Get the collection of slide IDs from the slide ID list.
            DocumentFormat.OpenXml.OpenXmlElementList slideIds = 
                presentation.SlideIdList.ChildElements;

            // If the slide ID is in range...
            if (slideIndex < slideIds.Count)
            {
                // Get the relationship ID of the slide.
                string slidePartRelationshipId = (slideIds[slideIndex] as SlideId).RelationshipId;

                // Get the specified slide part from the relationship ID.
                SlidePart slidePart = 
                    (SlidePart)presentationPart.GetPartById(slidePartRelationshipId);

                // Pass the slide part to the next method, and
                // then return the array of strings that method
                // returns to the previous method.
                return GetAllTextInSlide(slidePart);
            }
        }
    }

    // Else, return null.
    return null;
}
public static string[] GetAllTextInSlide(SlidePart slidePart)
{
    // Verify that the slide part exists.
    if (slidePart == null)
    {
        throw new ArgumentNullException("slidePart");
    }

    // Create a new linked list of strings.
    LinkedList<string> texts = new LinkedList<string>();

    // If the slide exists...
    if (slidePart.Slide != null)
    {
        // Iterate through all the paragraphs in the slide.
        foreach (DocumentFormat.OpenXml.Drawing.Paragraph paragraph in 
            slidePart.Slide.Descendants<DocumentFormat.OpenXml.Drawing.Paragraph>())
        {
            // Create a new string builder.                    
            StringBuilder paragraphText = new StringBuilder();

            // Iterate through the lines of the paragraph.
            foreach (DocumentFormat.OpenXml.Drawing.Text text in 
                paragraph.Descendants<DocumentFormat.OpenXml.Drawing.Text>())
            {
                // Append each line to the previous lines.
                paragraphText.Append(text.Text);
            }

            if (paragraphText.Length > 0)
            {
                // Add each paragraph to the linked list.
                texts.AddLast(paragraphText.ToString());
            }
        }
    }

    if (texts.Count > 0)
    {
        // Return an array of strings.
        return texts.ToArray();
    }
    else
    {
        return null;
    }
}
' Get all the text in a slide.
Public Function GetAllTextInSlide(ByVal presentationFile As String, ByVal slideIndex As Integer) As String()
    ' Open the presentation as read-only.
    Using presentationDocument As PresentationDocument = presentationDocument.Open(presentationFile, False)
        ' Pass the presentation and the slide index
        ' to the next GetAllTextInSlide method, and
        ' then return the array of strings it returns. 
        Return GetAllTextInSlide(presentationDocument, slideIndex)
    End Using
End Function
Public Function GetAllTextInSlide(ByVal presentationDocument As PresentationDocument, ByVal slideIndex As Integer) As String()
    ' Verify that the presentation document exists.
    If presentationDocument Is Nothing Then
        Throw New ArgumentNullException("presentationDocument")
    End If

    ' Verify that the slide index is not out of range.
    If slideIndex < 0 Then
        Throw New ArgumentOutOfRangeException("slideIndex")
    End If

    ' Get the presentation part of the presentation document.
    Dim presentationPart As PresentationPart = presentationDocument.PresentationPart

    ' Verify that the presentation part and presentation exist.
    If presentationPart IsNot Nothing AndAlso presentationPart.Presentation IsNot Nothing Then
        ' Get the Presentation object from the presentation part.
        Dim presentation As Presentation = presentationPart.Presentation

        ' Verify that the slide ID list exists.
        If presentation.SlideIdList IsNot Nothing Then
            ' Get the collection of slide IDs from the slide ID list.
            Dim slideIds = presentation.SlideIdList.ChildElements

            ' If the slide ID is in range...
            If slideIndex < slideIds.Count Then
                ' Get the relationship ID of the slide.
                Dim slidePartRelationshipId As String = (TryCast(slideIds(slideIndex), SlideId)).RelationshipId

                ' Get the specified slide part from the relationship ID.
                Dim slidePart As SlidePart = CType(presentationPart.GetPartById(slidePartRelationshipId), SlidePart)

                ' Pass the slide part to the next method, and
                ' then return the array of strings that method
                ' returns to the previous method.
                Return GetAllTextInSlide(slidePart)
            End If
        End If
    End If

    ' Else, return null.
    Return Nothing
End Function
Public Function GetAllTextInSlide(ByVal slidePart As SlidePart) As String()
    ' Verify that the slide part exists.
    If slidePart Is Nothing Then
        Throw New ArgumentNullException("slidePart")
    End If

    ' Create a new linked list of strings.
    Dim texts As New LinkedList(Of String)()

    ' If the slide exists...
    If slidePart.Slide IsNot Nothing Then
        ' Iterate through all the paragraphs in the slide.
        For Each paragraph In slidePart.Slide.Descendants(Of DocumentFormat.OpenXml.Drawing.Paragraph)()
            ' Create a new string builder.                    
            Dim paragraphText As New StringBuilder()

            ' Iterate through the lines of the paragraph.
            For Each Text In paragraph.Descendants(Of DocumentFormat.OpenXml.Drawing.Text)()
                ' Append each line to the previous lines.
                paragraphText.Append(Text.Text)
            Next Text

            If paragraphText.Length > 0 Then
                ' Add each paragraph to the linked list.
                texts.AddLast(paragraphText.ToString())
            End If
        Next paragraph
    End If

    If texts.Count > 0 Then
        ' Return an array of strings.
        Return texts.ToArray()
    Else
        Return Nothing
    End If
End Function

Siehe auch

Referenz

Class Library Reference