Jump to content

Macros/Writer/002/es

From The Document Foundation Wiki
This page is a translated version of the page Macros/Writer/002 and the translation is 100% complete.


Descripción

El menú Editar ▸ Enlaces permite reconocer los enlaces presentes en un documento, e incluye:

  • Fuente de archivo (URL)
  • Elemento (rango)
  • Tipo (soffice)
  • Actualizar (automático/manual)

Por otro lado, ni con este enfoque, ni el navegador le permiten saber cuáles son las tablas en cuestión (nombre o posición en el documento).

El propósito de esta macro es ubicar las tablas creadas por enlaces DDE. [1]

La macro inserta en la primera celda de una tabla, un comentario que consiste en:

  • Origen (URL de una hoja de cálculo de calc, por ejemplo),
  • El intervalo (de la fuente) utilizado

(Más sobre manipulación de comentarios con macros en Insertar un comentario en la posición del cursor .)

Tenga en cuenta que la colección TextFieldMasters solo devuelve la información mostrada por el menú Editar ▸ Enlaces y TextTables no nos da mucha información.

La conexión DDE de los datos de la tabla está contenida en un elemento <office:dde-source>[2].

Por lo tanto, podemos explorar el archivo content.xml para buscar dichos elementos. El programa comienza verificando que el documento actual tiene este archivo y luego procede a leerlo.

Para ello haremos uso del servicio com.sun.star.xml.sax.Parser[3] asociado son el listner com.sun.star.xml.sax.XDocumentHandler[4].

Código

en LibreOffice Basic:

Option Explicit

' This library is Copyright (C) 2012 Pierre-Yves Samyn, except otherwise indicated
' Purpose: Frame the selection or create an empty frame if no selection

' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation, either version 3 of the License, or
' (at your option) any later version.
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU General Public License for more details.
' You should have received a copy of the GNU General Public License
' along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
Dim oDoc As Object
Dim oDocHandler As Object
Dim oTableName As String


' Descripción de la macro:

' Contexto  :  para documentos LibreOffice Writer (odt)
' Objetivo  :  identificar tablas enlazadas por DDE
' Función   :  insertar un comentario con (URL de la hoja de cálculo por ej.), y el intervalo

'Información sobre el uso del analizador de sax XML de UNO a través de la API:
' http://www.oooforum.org/forum/viewtopic.phtml?t=4907

Sub Comment_DDE_Table()

    Dim oContent As Object
    Dim oFlux As Object
    Dim oSaxParser As Object
    Dim oDocEventsHandler As Object
    Dim oInputSource As Object

    oDoc = ThisComponent

    ' Sólo inicia la macro si el documento es un documento de Writer
    If oDoc.supportsService("com.sun.star.text.TextDocument") Or _
        oDoc.supportsService("com.sun.star.text.GlobalDocument") Then

        ' Queremos leer el archivo content.xml, por lo que verificamos que "ThisComponent" haga referencia a un objeto con dicho archivo
        If oDoc.DocumentStorage.HasByName("content.xml") Then
        
            ' Comprueba si el documento se ha modificado: leeremos el archivo content.xml 
' por lo que solicitamos que se guarde para trabajar con el contenido más reciente.
            If oDoc.ismodified Then
                MsgBox "¡El documento debe guardarse en su última versión! (Ctrl + S)", 64, "Comment_DDE_Table()"
            Else 
                oContent = oDoc.DocumentStorage.GetByName("content.xml")
                oFlux = oContent.GetInputStream()   
                        
                ' Crear un analizador de Sax XML
                oSaxParser = createUnoService( "com.sun.star.xml.sax.Parser" )
                
                ' Crear administrador de sucesos.
                'Los nombres que se dan a continuación reflejan contenido de acuerdo con
                ' http://api.libreoffice.org/common/ref/com/sun/star/xml/sax/XDocumentHandler.html
                oDocHandler = CreateUnoListener( "DocHandler_", "com.sun.star.xml.sax.XDocumentHandler" )
                oSaxParser.setDocumentHandler( oDocHandler )
                   
                ' Creación de la estructura de acuerdo con:
                ' http://api.libreoffice.org/common/ref/com/sun/star/xml/sax/InputSource.html

                oInputSource = createUnoStruct( "com.sun.star.xml.sax.InputSource" )
                oInputSource.aInputStream = oFlux
        
                ' Indicar al Parser que lea el contenido de content.xml
                'Las funciones (DocHandler_) se llamarán de acuerdo con el suceso.
                oSaxParser.parseStream( oInputSource )
                oFlux.closeInput()
                        
                MsgBox "Fin del tratamiento" , 64, "Comment_DDE_Table()"
            End If
        Else
            MsgBox "Esta macro no funciona para este tipo de documento (debe ser archivo de Writer odt)" , 64, "Comment_DDE_Table()"
        End If

        Else
        MsgBox "Esta macro no funciona para este tipo de documento (debe ser archivo de Writer odt)" , 64, "Comment_DDE_Table()"
    End If

End Sub ' Comment_DDE_Table


' A continuación, las funciones del listener, correspondientes a los sucesos:
' http://api.libreoffice.org/common/ref/com/sun/star/xml/sax/XDocumentHandler.html

Sub DocHandler_startDocument()
End Sub

Sub DocHandler_endDocument()
End Sub

Sub DocHandler_startElement( cName As String, oAttributes As com.sun.star.xml.sax.XAttributeList )

    Dim oTable As Object
    Dim oCursor As Object
    Dim oComment As Object

    Dim oDateHour As New com.sun.star.util.DateTime

    ' Si el elemento es una tabla, almacene su nombre
    If cName = "table:table" Then
        oTableName = oAttributes.getValueByName("table:name")
    End If   

    ' Consulte OASIS Documento de formato abierto para aplicaciones de oficina:
  ' http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os.html
  ' La conexión de datos DDE de tablas está contenida en un elemento <office:dde-source>.
  ' El uso de este elemento difiere entre hojas de cálculo y tablas en documentos de texto. 
  ' Para tablas en documentos de texo, el elemento está contenido en el elemento tabla <table:table> directamente.
    'Por lo tanto, comprueba si la tabla está vinculada a DDE:
    If cName = "office:dde-source" Then

        ' Acceso a la tabla:
        oTable = oDoc.TextTables.getByName(oTableName)

        ' Crear un cursor en la primera celda de la tabla
        oCursor = oTable.getCellByPosition(0, 0).createTextCursor

        ' Crear un comentario
        oComment = oDoc.createInstance("com.sun.star.text.textfield.Annotation")

        ' Obtener datos de fecha/hora
        With oDateHour
            .Minutes = minute(now)
            .Hours = hour(now)
            .Day = day(now)
            .Month = month(now)
            .Year = year(now)
        End With
         
        ' completar el comentario con origen e intervalo de objeto DDE
        With oComment
            .Author = "Source: DDE link"
            .Content = oAttributes.getValueByName("office:dde-item") & chr(13) &_
                oAttributes.getValueByName("office:dde-topic")
            .DateTimeValue = oDateHour
        End With

        ' Insertar el comentario en la celda
        oComment.attach(oCursor.start)
    End If

End Sub ' DocHandler_startElement


Sub DocHandler_endElement( cName As String )
End Sub

Sub DocHandler_characters( cChars As String )
End Sub

Sub DocHandler_ignorableWhitespace( cWhitespace As String )
End Sub

Sub DocHandler_processingInstruction( cTarget As String, cData As String )
End Sub

Sub DocHandler_setDocumentLocator( oLocator As com.sun.star.xml.sax.XLocator )
End Sub

Notes

  1. DDE: "intercambio dinámico de datos", le permite vincular objetos por referencia a los archivos, sin integrarlos.
  2. Consulte el estándar OASIS Formato de Documento abierto para aplicaciones de oficina. El uso de este elemento difiere entre una hoja de cálculo y procesamiento de texto. Para los documentos de texto, el elemento está contenido directamente dentro del elemento <table:table>.
  3. Consulte la documentación de la API sobre com.sun.star.xml.sax.Parser
  4. Consulte la documentación de la API sobre com.sun.star.xml.sax.XDocumentHandler