Issues with Reporting and adding charts

Getting your data onto paper - or the web - Discussing the reports features of Base
Post Reply
gdebruin
Posts: 1
Joined: Tue Sep 08, 2015 4:14 pm

Issues with Reporting and adding charts

Post by gdebruin »

I am using open office for mac and I am having ongoing issues with my reporting. The minute I add any chart of any form or shape
to my report the open office application terminate without giving a good reason why.

I am no expert with OO but I cannot imagine how a chart without any fields properties being set can cause the entire system to shut down.

Is there anyone that can help with this? I have tried both with my data from 2 separate tables and then joining the chart data to the report
data and also just tried using an empty report but in both scenarios the application terminates the minute that I try to save the report.

In advance thanks
NeoOffice 2.2.3 with MacOS 10.4
User avatar
Villeroy
Volunteer
Posts: 31269
Joined: Mon Oct 08, 2007 1:35 am
Location: Germany

Re: Issues with Reporting and adding charts

Post by Villeroy »

You can use Calc as alternative reporting tool with charts.
[Tutorial] Using registered datasources in Calc
Create a linked import range and charts.
Please, edit this topic's initial post and add "[Solved]" to the subject line if your problem has been solved.
Ubuntu 18.04 with LibreOffice 6.0, latest OpenOffice and LibreOffice
Nocton
Volunteer
Posts: 533
Joined: Fri Nov 05, 2010 10:27 am
Location: UK

Re: Issues with Reporting and adding charts

Post by Nocton »

Since OO 3.4 the chart option in reports has not worked. So as Villeroy says, the only alternative is to use Calc. That is a good option expect that you cannot have it at the same time as your Base report.

I have not had any crashes, just after 3.4 reports that had charts and worked OK no longer worked. I assume that you are using the Oracle Report writer extension?

Regards,

Nocton
OpenOffice 4.1.12 on Windows 10
longi
Posts: 110
Joined: Mon Jul 15, 2013 5:04 pm

Re: Issues with Reporting and adding charts

Post by longi »

Hi!

Here you have an example. I used two different macros in order to put a chart inside a report: one ORB and the other is an old-fashioned report.
I know nothing about programing, and people who know to do things could think that I am a mad person, but those macros work.

Bye!
Attachments
INFORMES 33 - copia.7z
(127.62 KiB) Downloaded 327 times
OpenOffice 4.1.5 on Windows 10
LibreOffice 5.1 on Windows 7
LibreOffice 6.0.1 on Windows10
Nocton
Volunteer
Posts: 533
Joined: Fri Nov 05, 2010 10:27 am
Location: UK

Re: Issues with Reporting and adding charts

Post by Nocton »

Very interesting, longi - especially when you say: "I know nothing about programing".

However, although the report certainly contains charts, I cannot see how to insert the chart in the first place starting with a new report.

Regards

Nocton
OpenOffice 4.1.12 on Windows 10
longi
Posts: 110
Joined: Mon Jul 15, 2013 5:04 pm

Re: Issues with Reporting and adding charts

Post by longi »

Hi!
Yes, I Know nothing about programming. I only know about copying and pasting from other authors....I also know nothing about English, so it is possible I didn't catch correctly what you want to explain.
If you want to have the chart at the begining of the report, in the old fashioned report only is neccesary to make minimal changes in the macro:

Code: Select all

Sub InsercionGraficoMultiserie
    '--------------------------------------------------------------------
    ' 0 Declaramos las variables
    
    Dim oreportdoc As Variant, ocontroller As Variant, oTexttable As Object
    Dim oText As Variant, oCurs As Object, oPar As Object
    Dim Conn As Variant, oStat As Variant, oSQLQuery As Variant
    Dim i As Integer, a As Integer, J As Integer, k As Integer, Filas As Integer, Columnas As Integer, co1 As Integer
    Dim oResultSet As Variant, oEmbeded As Object, oChartdoc As variant 
    Dim mDirectorio As Variant, sTmp As Variant, oData As Variant, oArea As Variant, oDiagram As Variant, oDatos As Variant
    Dim oFondo As Variant, oXAxisTitle As Variant, oYAxisTitle As Variant, oZAxisTitle As Variant 
    Dim oEjeZ As Variant, oEjeX As Variant, oEjeY As Variant, oTituloEje As Variant
    '-------------------------------------------------------------------------
    ' 1º Abrimos el informe
    
    ocontroller = Thisdatabasedocument.currentController
    if not ocontroller.isconnected then ocontroller.connect                                        ' Mantenemos la conexión
    oreportdoc = Thisdatabasedocument.reportdocuments.getbyname("COMARCAS").open                   ' Abrimos el informe
    oTexttable = oreportdoc.Texttables(0)                                                          ' La única tabla del informe
    '----------------------------------------------------------
    ' 2º Ponemos un párrafo delante de la tabla

    oText = oreportdoc.getText()                                                                   ' Texto del informe
    oCurs = oText.createTextCursor()                                                               ' Generamos el cursor
    oPar = oreportdoc.createInstance("com.sun.star.text.Paragraph")                                ' Estructura de párrafo 
    oText.insertTextContentBefore ( oPar,oTexttable )                                               ' Insertamos el párrafo detrás de la tabla

    '--------------------------------------------------------------------------------  
    ' 3º Ponemos el cursor de tabla fuera de la tabla 
    
    oCurs = oreportdoc.getCurrentController().getViewCursor()                                      ' Generamos cursor de tabla
    oCurs.gotoStart(False)                                                                           ' Cursor al final de la primera celda
    'oCurs.gotoEnd(False)                                                                           ' Cursor al final de la tabla
    oCurs.goUp(1,False)                                                                          ' Sacamos el cursor de la tabla al párrafo generado antes
    '-------------------------------------------------------------------------  
    ' 4º Establecemos el origen de la tabla que añadimos
    
    Conn = ThisDatabaseDocument.CurrentController.ActiveConnection                                 ' Conectamos para recoger los datos de las tablas
    oStat=Conn.createStatement()                                                                   ' Creación de la conexión
    oSQLQuery =  "SELECT  ""CONCELLOS"".""COMARCA"",SUM( CASEWHEN( ""Días Notificaión"" < 15, 1, 0 ) ) AS ""MENOS DE 15"", SUM( CASEWHEN( ""Días Notificaión"" >= 15, 1, 0 ) - CASEWHEN( ""Días Notificaión"" > 29, 1, 0 ) ) AS ""ENTRE 15 Y 30"", SUM( CASEWHEN( ""Días Notificaión"" > 29, 1, 0 ) - CASEWHEN( ""Días Notificaión"" > 45, 1, 0 ) ) AS ""ENTRE 30 Y 45"", SUM( CASEWHEN( ""Días Notificaión"" > 45, 1, 0 ) ) AS ""MAS DE 45"" FROM ""CONSULC"", ""CONCELLOS"" WHERE ""CONSULC"".""CODIGO CONCELLO"" = ""CONCELLOS"".""Cod_Conc"" GROUP BY ""CONCELLOS"".""COMARCA"""
    oStat.setPropertyValue("ResultSetType",1005)                                                   ' Características de la consulta
    oResultSet = oStat.executeQuery(oSQLQuery)                                                     ' Se ejecuta la consulta
    oResultSet.last                                                                                ' Va al último registro para contar los registros que tiene
    Filas = oResultSet.Row                                                                         ' Añade la variable con el número de registros devuelto 
    oResultSet.first                                                                               ' Mueve el cursor al primer registro
    oResultSet.previous 
    Columnas= oResultSet.Columns.Count                                                             ' Número de columnas que tiene el resultado de la consulta 
    '------------------------------------------------------------------------------- 
    ' 5º Conseguimos un array de los nombres de las columnas, en este caso menos de la primera, la usamos al final de la macro
    
    Dim oMeta                                                                                      ' Denominación del array
    oMeta = oResultSet.getMetaData()                                                               ' Recoge los metadatos del resulset (cabecera de columnas)
    k=0                                                                                            ' Inicio para k=0
    Dim ColumnArray()                                                                              ' Array de columnas
    for i=2 to Columnas                                                                            ' Desde la segunda columna hasta la última
    Redim Preserve ColumnArray(K)                                                                  ' Se redimensiona la matriz
    ColumnArray(K) = oMeta.getColumnName(i)                                                        ' Se recogen los datos del array de columnas y se graba en el array meta
	K = K+1                                                                                        ' Se avanza a la siguiente columna
	next i                                                                                         ' Se sigue con el ciclo
	'-------------------------------------------------------------------------
	' 6º Conseguimos los datos del ResultSet en la primera columna
    
    k = 0                                                                                          ' Inicio de la instrucción en k=0
    Dim RowArray()                                                                                 ' Definición del Array      
    While oResultSet.next                                                                          ' Hacemos avanzar en el ResultSet
    Redim Preserve RowArray(k)                                                                     ' Redimensionamos el Array
	RowArray(k) = oResultset.getString(1)                                                          ' Establecemos el valor dentro del Array
	k = k+1                                                                                        ' Ir al siguiente registro  
    Wend                                                                                           ' Acaba el ciclo

    '--------------------------------------------------------------------
    ' 7º  Recurrimos al inicio del ResultSet
     
    oResultSet.first                                                                               ' Mueve el cursor al primer registro del ResultSet
    oResultSet.previous                                                                            ' Pone el cursor por encima del primer registro
    '--------------------------------------------------------------------
    ' 8º Ponemos un gráfico al final de la tabla

    oEmbeded = oreportdoc.createInstance("com.sun.star.text.TextEmbeddedObject")                   ' Estructura de objeto embebido
    oEmbeded.setPropertyValue("CLSID","12DCAE26-281F-416F-a234-c3086127382e")                      ' El objeto es un gráfico
    oText.insertTextContent(oCurs,oEmbeded,True)                                                   ' Ponemos el objeto embebido en el cursor de texto que se hizo en el paso 2º
    oChartDoc = oEmbeded.getEmbeddedObject()                                                       ' Tomamos el control del gráfico
    '-------------------------------------------------------------------
    ' 9º Título del gráfico
  
    oChartDoc.getTitle().String = "SACOS DE PATATAS"                                               ' Establecemos el título del gráfico
    oChartDoc.getTitle().CharHeight=8                                                              ' Tamaño de letra que le aplicamos
    '---------------------------------------------------------------------------
    ' 10º Subtítulo del gráfico
    
    oChartDoc.getSubTitle().String =""                                                             ' Dejamos en blanco el subtítulo 
    oChartDoc.getSubTitle().CharHeight=8                                                           ' Tamaño de la letra que tendría si hubiese sutítulo
    '----------------------------------------------------------------------------
    ' 11º Sacamos los datos del ResultSet hacia una matriz o Array de dimensión 2 (Esto es del libro de Mauricio)
    
    While oResultset.next                                                                          ' Iniciamos ciclo de revisión de todo el ResultSet
    for i=0 to Columnas-2                                                                          ' Ciclo que recorre las columnas del ResultSet
    Redim Preserve mDirectorio( co1,Columnas-2)                                                    ' Redimensionamos la matriz
    mDirectorio( co1,i) = oResultset.getString(i+2)                                                ' Guardamos los datos en el nuevo indice
    next                                                                                           ' Terminamos el ciclo de columnas
    sTmp = sTmp & mDirectorio( co1,i-1)                                                            ' Vamos construyendo nuestro directorio   
    co1 = co1 + 1                                                                                  ' Incrementamos nuestro contador de registros   
    Wend                                                                                           ' Acabamos de inspeccionar el ResutSet
    '---------------------------------------------------------------------------------- 
    ' 11º Accedemos a los datos del gráfico 
    
    oData = oChartDoc.Data                                                                        ' Datos del gráfico
    oData.setData(mDirectorio())                                                                  ' Insertamos los datos del array
    '-----------------------------------------------------------------------------------
    ' 12º Accedemos al área del gráfico para darla formato
    
    oArea = oChartDoc.Area                                                                        ' Area del gráfico     
    oArea.FillColor = RGB(240, 240, 240)                                                          ' Color del área en la que se asienta el gráfico 
    '---------------------------------------------------------------------------------
    ' 13º Tipo de diagrama

    oDiagram = oChartDoc.createInstance( "com.sun.star.chart.BarDiagram" )                       ' Diagrama de barras
    oChartDoc.getDiagram.Dim3D = True                                                            ' Tres dimensiones
    oChartDoc.getDiagram.Vertical = False                                                        ' True lo convierte en vertical
    oChartDoc.setDiagram( oDiagram )                                                             ' Se aplican las condiciones del diagrama
   ' oDatos = oChartDoc.getDiagram.getDataRowProperties(2)                                       ' Según el valor, varía el color de las barras
    oChartDoc.Diagram.Deep = true                                                                ' Las barras se colocan en profundidad
    oChartDoc.Diagram.D3DScenePerspective = com.sun.star.drawing.ProjectionMode.PERSPECTIVE      ' Añade perspectiva
    oChartDoc.Diagram.Perspective = 30                                                           ' Regulamos la cantidad de perspectiva que tenemos
    oChartDoc.Diagram.RotationHorizontal = 10                                                    ' Rotación horizontal
    oChartDoc.Diagram.RotationVertical = 10                                                      ' Rotación vertigal
    oFondo = oChartDoc.getDiagram.getWall                                                        ' Muro del gráfico
    oFondo.FillBackground = True                                                                 ' Rellenamos el fondo del muro
    oFondo.FillStyle = RGB(240,240,240)                                                          ' Aplicamos estilo en el muro
    oFondo.FillColor = RGB(140,240,140)                                                          ' Damos el último toque de color al muro
    oDiagram.hasXAxisTitle() = True                                                              ' Tiene título en X
    oXAxisTitle = oDiagram.XAxisTitle                                                            ' Accedemos al título en X
    oXAxisTitle.String = "COMARCAS"                                                              ' Título en X 
    oXAxisTitle.CharColor = 0                                                                    ' Color del título en X
    oXAxisTitle.CharHeight = 7                                                                   ' Tamaño de letra en título en X
    oDiagram.hasYAxisTitle() = True                                                              ' Tiene título en Y
    oYAxisTitle = oDiagram.YAxisTitle                                                            ' Accedemos al título en Y
    oYAxisTitle.String = "SACOS"                                                                 ' Título en Y
    oYAxisTitle.CharColor = 0                                                                    ' Color de título en Y
    oYAxisTitle.CharHeight = 7                                                                   ' Tamaño de letra en Y  
    oDiagram.hasZAxisTitle() = True                                                              ' Tiene título en Z 
    oZAxisTitle = oDiagram.ZAxisTitle                                                            ' Accedemos al título en Z
    oZAxisTitle.String = "DIAS DE RETRASO"                                                       ' Título en Z 
    oZAxisTitle.CharColor = 0                                                                    ' Color del título en Z
    oZAxisTitle.CharHeight = 6                                                                   ' Tamaño letra en título Z
    oZAxisTitle.TextRotation = 4500                                                              ' Rotación de 45º del título en Z
    oDiagram.hasXAxisGrid = True                                                                 ' Tiene líneas de fondo en X
    oDiagram.hasYAxisGrid = True                                                                 ' Tiene líneas de fondo en Y
    oChartDoc.HasLegend = False                                                                  ' Carece de leyenda
    '----------------------------------------------------------------------------
    ' 14º Describimos las series de datos
   
    oChartDoc.Data.setColumnDescriptions(ColumnArray())                                          ' Datos recogidos en el array del paso nº 5
    oEjeZ = oDiagram.getZAxis                                                                    ' Controlamos el eje Z 
    oEjeZ.CharHeight=7                                                                           ' Tamaño de la letra 
    oEjeZ.TextRotation = 0                                                                       ' Sin rotación
    '------------------------------------------------------------------------------
    ' 15º Describimos las columnas
    
    oChartDoc.Data.setRowDescriptions(RowArray())                                                ' Datos recogidos en el array del paso nº6
    oEjeX = oDiagram.getXAxis                                                                    ' Controlamos el eje  X
    oEjeX.CharHeight=7                                                                           ' Tamaño de la letra
    oEjeX.TextRotation = 9000                                                                    ' Giro de 90 grados 
   
    oEjeY = oDiagram.getYAxis                                                                    ' Controlamos el eje Y
    oEjeY.CharHeight=7                                                                           ' Tamaño de la letra
    oEjeY.TextRotation = 0                                                                       ' Sin rotación
    '--------------------------------------------------------------------------------
    ' 16º Tamaño del gráfico
   
    oEmbeded.width = 16000                                                                       ' Anchura del objeto embebido (gráfico)
    oEmbeded.Height= 9500                                                                       ' Altura del objeto embebido
    oEmbeded.HoriOrient =2                                                                       ' Centrado
    oEmbeded.AnchorType = com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH                   ' Anclaje al párrafo  
    oEmbeded.Surround = com.sun.star.text.WrapTextMode.DYNAMIC                                ' NONE, DYNAMIC, PARALLEL, LEFT, RIGHT
    '---------------------------------------------------------------------------------------
    ' 17º Añadimos párrafo al final
    
    oText.InsertControlCharacter(oText.getEnd(),com.sun.star.text.ControlCharacter.APPEND_PARAGRAPH, False)
    '-------------------------------------------------------------------------------------------  
    ' 17ºAñadimos una línea de texto
    
     oCurs.gotoEnd(False)                                                                        ' Colocamos el cursor de texto al final del informe    
     oText.insertString(oCurs,CHR$(13) & "Al fín terminé.....", False)                           ' Colocamos un final triunfante.

End Sub 
All my efforts about programming had been made out of ORB, so I don't know today how to get the same visual results. However, changing a bit more things than in the first macro,
 Edit: (and deleting the labels in the header of the table in the deing of the report ) 
we can have a similar result, except that it run in two pages, one of them for the chart and the other for the table:

Code: Select all

Sub InsercionGraficoMultiserie
    '--------------------------------------------------------------------
    ' 0 Declaramos las variables
    
    Dim oreportdoc As Variant, ocontroller As Variant, oTexttable As Object
    Dim oText As Variant, oCurs As Object, oPar As Object
    Dim Conn As Variant, oStat As Variant, oSQLQuery As Variant
    Dim i As Integer, a As Integer, J As Integer, k As Integer, Filas As Integer, Columnas As Integer, co1 As Integer
    Dim oResultSet As Variant, oEmbeded As Object, oChartdoc As variant 
    Dim mDirectorio As Variant, sTmp As Variant, oData As Variant, oArea As Variant, oDiagram As Variant, oDatos As Variant
    Dim oFondo As Variant, oXAxisTitle As Variant, oYAxisTitle As Variant, oZAxisTitle As Variant 
    Dim oEjeZ As Variant, oEjeX As Variant, oEjeY As Variant, oTituloEje As Variant
    '-------------------------------------------------------------------------
    ' 1º Abrimos el informe
    
    ocontroller = Thisdatabasedocument.currentController
    if not ocontroller.isconnected then ocontroller.connect                                        ' Mantenemos la conexión
    oreportdoc = Thisdatabasedocument.reportdocuments.getbyname("COMARCAS2").open                  ' Abrimos el informe
    oTexttable = oreportdoc.Texttables(2)                                                          ' La tabla del informe
    '-------------------------------------------------------------------------
    ' 2º Ponemos encabezamiento de la tabla
    
    oTexttable.Rows.insertByIndex(0,1)                                                             ' Inserta una nueva línea al principio de la tabla
    Filas= oTexttable.rows.count-1                                                                 ' Número de filas que tiene la tabla
    Columnas= oTexttable.Columns.Count-1                                                           ' Número de columnas de la tabla
    oTexttable.getCellByPosition(0,0).setString("Comarca")                                         ' Texto en la primera celda
    oTexttable.getCellByPosition(1,0).setString("Concello")                                        ' Texto en la segunda
    oTexttable.getCellByPosition(2,0).setString("Cod.Com")                                         ' Texto en la tercera
    '---------------------------------------------------------------------------
    ' 3º Damos formato al texto de la cabecera

    for a = 0 to Columnas                                                                          ' Trabajamos en todas las columnas
    oCell = oTextTable.getCellByPosition(a, 0)                                                     ' Celdas que cumplen las condiciones                  
    oText = oCell.Text                                                                             ' Texto en el interior de la celda
    oCurs = oText.createTextCursor()                                                               ' Generamos un cursor de texto
    oCurs.gotoEND(True)                                                                            ' Vamos hasta el final del texto, indicando que las acciones se aplican a todo el texto de la celda
    oCurs.CharFontName = "Arial"                                                                   ' Nombre de la fuente
    oCurs.CharWeight = com.sun.star.awt.FontWeight.BOLD                                            ' Negrita
    oCurs.CharColor = RGB(0,0,0)                                                                   ' Color del texto
    oCurs.CharHeight = 12                                                                          ' Tamaño de la letra
    oCurs.CharPosture = com.sun.star.awt.FontSlant.ITALIC                                          ' Cursiva
    oCurs.ParaAdjust = com.sun.star.style.ParagraphAdjust.CENTER                                   ' Centrada
    oCell.setPropertyValue("BackColor", RGB(255, 255, 0))                                          ' El color que ponemos
    Next a                                                                                         ' Cerramos ciclo de columnas
    '-------------------------------------------------------------------------
    '2º Generamos la estructura de borde                                                          
    
    oBorder = CreateUnoStruct("com.sun.star.table.BorderLine")                                     ' Generamos la estructura de borde
    oBorder.Color = RGB(0, 0, 0)                                                                ' Color del borde
    oBorder.OuterLineWidth = 5                                                                    ' Anchura del borde
    '-------------------------------------------------------------------------
    '3º Escogemos las celdas para  modificar sus bordes
    
    For i =0 To Columnas                                                                           ' Ciclo que recorre todas las columnas
    for a = 0 to Filas                                                                             ' Ciclo que recorre todas las filas
    oCell = oTexttable.getCellByPosition(i,a)                                                      ' Todas las celdas de la tabla
    oCell.RightBorder = oBorder                                                                    ' Borde derecho
    oCell.TopBorder = oBorder                                                                      ' Borde superior
    oCell.BottomBorder = oBorder                                                                   ' Borde inferior
    oCell.leftBorder = oBorder                                                                     ' Borde izquierdo
    Next a                                                                                         ' Cierra el ciclo de las filas
    Next i       

    '----------------------------------------------------------
    ' 4º Ponemos un párrafo delante de la tabla
    
    oText = oreportdoc.getText()                                                                   ' Texto del informe
    oCurs = oText.createTextCursor()                                                               ' Generamos el cursor
    oPar = oreportdoc.createInstance("com.sun.star.text.Paragraph")                                ' Estructura de párrafo 
    oText.insertTextContentBefore ( oPar,oTexttable )                                              ' Insertamos el párrafo detrás de la tabla
    '--------------------------------------------------------------------------------  
    ' 5º Ponemos el cursor de tabla fuera de la tabla 
    
    oCurs = oreportdoc.getCurrentController().getViewCursor()                                      ' Generamos cursor de tabla
    oCurs.gotoStart(False)                                                                         ' Cursor al principio de la primera celda
    oCurs.goup(1,False)                                                                            ' Sacamos el cursor de la tabla al párrafo generado antes
    '-------------------------------------------------------------------------  
    ' 6º Establecemos el origen de la tabla que añadimos
    
    Conn = ThisDatabaseDocument.CurrentController.ActiveConnection                                 ' Conectamos para recoger los datos de las tablas
    oStat=Conn.createStatement()                                                                   ' Creación de la conexión
    oSQLQuery =  "SELECT  ""CONCELLOS"".""COMARCA"",SUM( CASEWHEN( ""Días Notificaión"" < 15, 1, 0 ) ) AS ""MENOS DE 15"", SUM( CASEWHEN( ""Días Notificaión"" >= 15, 1, 0 ) - CASEWHEN( ""Días Notificaión"" > 29, 1, 0 ) ) AS ""ENTRE 15 Y 30"", SUM( CASEWHEN( ""Días Notificaión"" > 29, 1, 0 ) - CASEWHEN( ""Días Notificaión"" > 45, 1, 0 ) ) AS ""ENTRE 30 Y 45"", SUM( CASEWHEN( ""Días Notificaión"" > 45, 1, 0 ) ) AS ""MAS DE 45"" FROM ""CONSULC"", ""CONCELLOS"" WHERE ""CONSULC"".""CODIGO CONCELLO"" = ""CONCELLOS"".""Cod_Conc"" GROUP BY ""CONCELLOS"".""COMARCA"""
    oStat.setPropertyValue("ResultSetType",1005)                                                   ' Características de la consulta
    oResultSet = oStat.executeQuery(oSQLQuery)                                                     ' Se ejecuta la consulta
    oResultSet.last                                                                                ' Va al último registro para contar los registros que tiene
    Filas = oResultSet.Row                                                                         ' Añade la variable con el número de registros devuelto 
    oResultSet.first                                                                               ' Mueve el cursor al primer registro
    oResultSet.previous 
    Columnas= oResultSet.Columns.Count                                                             ' Número de columnas que tiene el resultado de la consulta 
    '------------------------------------------------------------------------------- 
    ' 7º Conseguimos un array de los nombres de las columnas, en este caso menos de la primera, la usamos al final de la macro
    
    Dim oMeta                                                                                      ' Denominación del array
    oMeta = oResultSet.getMetaData()                                                               ' Recoge los metadatos del resulset (cabecera de columnas)
    k=0                                                                                            ' Inicio para k=0
    Dim ColumnArray()                                                                              ' Array de columnas
    for i=2 to Columnas                                                                            ' Desde la segunda columna hasta la última
    Redim Preserve ColumnArray(K)                                                                  ' Se redimensiona la matriz
    ColumnArray(K) = oMeta.getColumnName(i)                                                        ' Se recogen los datos del array de columnas y se graba en el array meta
	K = K+1                                                                                        ' Se avanza a la siguiente columna
	next i                                                                                         ' Se sigue con el ciclo
	'-------------------------------------------------------------------------
	' 8º Conseguimos los datos del ResultSet en la primera columna
    
    k = 0                                                                                          ' Inicio de la instrucción en k=0
    Dim RowArray()                                                                                 ' Definición del Array      
    While oResultSet.next                                                                          ' Hacemos avanzar en el ResultSet
    Redim Preserve RowArray(k)                                                                     ' Redimensionamos el Array
	RowArray(k) = oResultset.getString(1)                                                          ' Establecemos el valor dentro del Array
	k = k+1                                                                                        ' Ir al siguiente registro  
    Wend                                                                                           ' Acaba el ciclo

    '--------------------------------------------------------------------
    ' 9º  Recurrimos al inicio del ResultSet
     
    oResultSet.first                                                                               ' Mueve el cursor al primer registro del ResultSet
    oResultSet.previous                                                                            ' Pone el cursor por encima del primer registro
    '--------------------------------------------------------------------
    ' 10º Ponemos un gráfico al final de la tabla

    oEmbeded = oreportdoc.createInstance("com.sun.star.text.TextEmbeddedObject")                   ' Estructura de objeto embebido
    oEmbeded.setPropertyValue("CLSID","12DCAE26-281F-416F-a234-c3086127382e")                      ' El objeto es un gráfico
    oText.insertTextContent(oCurs,oEmbeded,True)                                                   ' Ponemos el objeto embebido en el cursor de texto que se hizo en el paso 2º
    oChartDoc = oEmbeded.getEmbeddedObject()                                                       ' Tomamos el control del gráfico
    '-------------------------------------------------------------------
    ' 11º Título del gráfico
  
    oChartDoc.getTitle().String = "SACOS DE PATATAS"                                               ' Establecemos el título del gráfico
    oChartDoc.getTitle().CharHeight=8                                                              ' Tamaño de letra que le aplicamos
    '---------------------------------------------------------------------------
    ' 12º Subtítulo del gráfico
    
    oChartDoc.getSubTitle().String =""                                                             ' Dejamos en blanco el subtítulo 
    oChartDoc.getSubTitle().CharHeight=8                                                           ' Tamaño de la letra que tendría si hubiese sutítulo
    '----------------------------------------------------------------------------
    ' 13º Sacamos los datos del ResultSet hacia una matriz o Array de dimensión 2 (Esto es del libro de Mauricio)
    
    While oResultset.next                                                                          ' Iniciamos ciclo de revisión de todo el ResultSet
    for i=0 to Columnas-2                                                                          ' Ciclo que recorre las columnas del ResultSet
    Redim Preserve mDirectorio( co1,Columnas-2)                                                    ' Redimensionamos la matriz
    mDirectorio( co1,i) = oResultset.getString(i+2)                                                ' Guardamos los datos en el nuevo indice
    next                                                                                           ' Terminamos el ciclo de columnas
    sTmp = sTmp & mDirectorio( co1,i-1)                                                            ' Vamos construyendo nuestro directorio   
    co1 = co1 + 1                                                                                  ' Incrementamos nuestro contador de registros   
    Wend                                                                                           ' Acabamos de inspeccionar el ResutSet
    '---------------------------------------------------------------------------------- 
    ' 14º Accedemos a los datos del gráfico 
    
    oData = oChartDoc.Data                                                                        ' Datos del gráfico
    oData.setData(mDirectorio())                                                                  ' Insertamos los datos del array
    '-----------------------------------------------------------------------------------
    ' 15º Accedemos al área del gráfico para darla formato
    
    oArea = oChartDoc.Area                                                                        ' Area del gráfico     
    oArea.FillColor = RGB(240, 240, 240)                                                          ' Color del área en la que se asienta el gráfico 
    '---------------------------------------------------------------------------------
    ' 16º Tipo de diagrama

    oDiagram = oChartDoc.createInstance( "com.sun.star.chart.BarDiagram" )                       ' Diagrama de barras
    oChartDoc.getDiagram.Dim3D = True                                                            ' Tres dimensiones
    oChartDoc.getDiagram.Vertical = False                                                        ' True lo convierte en vertical
    oChartDoc.setDiagram( oDiagram )                                                             ' Se aplican las condiciones del diagrama
   ' oDatos = oChartDoc.getDiagram.getDataRowProperties(2)                                       ' Según el valor, varía el color de las barras
    oChartDoc.Diagram.Deep = true                                                                ' Las barras se colocan en profundidad
    oChartDoc.Diagram.D3DScenePerspective = com.sun.star.drawing.ProjectionMode.PERSPECTIVE      ' Añade perspectiva
    oChartDoc.Diagram.Perspective = 30                                                           ' Regulamos la cantidad de perspectiva que tenemos
    oChartDoc.Diagram.RotationHorizontal = 10                                                    ' Rotación horizontal
    oChartDoc.Diagram.RotationVertical = 10                                                      ' Rotación vertigal
    oFondo = oChartDoc.getDiagram.getWall                                                        ' Muro del gráfico
    oFondo.FillBackground = True                                                                 ' Rellenamos el fondo del muro
    oFondo.FillStyle = RGB(240,240,240)                                                          ' Aplicamos estilo en el muro
    oFondo.FillColor = RGB(140,240,140)                                                          ' Damos el último toque de color al muro
    oDiagram.hasXAxisTitle() = True                                                              ' Tiene título en X
    oXAxisTitle = oDiagram.XAxisTitle                                                            ' Accedemos al título en X
    oXAxisTitle.String = "COMARCAS"                                                              ' Título en X 
    oXAxisTitle.CharColor = 0                                                                    ' Color del título en X
    oXAxisTitle.CharHeight = 7                                                                   ' Tamaño de letra en título en X
    oDiagram.hasYAxisTitle() = True                                                              ' Tiene título en Y
    oYAxisTitle = oDiagram.YAxisTitle                                                            ' Accedemos al título en Y
    oYAxisTitle.String = "SACOS"                                                                 ' Título en Y
    oYAxisTitle.CharColor = 0                                                                    ' Color de título en Y
    oYAxisTitle.CharHeight = 7                                                                   ' Tamaño de letra en Y  
    oDiagram.hasZAxisTitle() = True                                                              ' Tiene título en Z 
    oZAxisTitle = oDiagram.ZAxisTitle                                                            ' Accedemos al título en Z
    oZAxisTitle.String = "DIAS DE RETRASO"                                                       ' Título en Z 
    oZAxisTitle.CharColor = 0                                                                    ' Color del título en Z
    oZAxisTitle.CharHeight = 6                                                                   ' Tamaño letra en título Z
    oZAxisTitle.TextRotation = 4500                                                              ' Rotación de 45º del título en Z
    oDiagram.hasXAxisGrid = True                                                                 ' Tiene líneas de fondo en X
    oDiagram.hasYAxisGrid = True                                                                 ' Tiene líneas de fondo en Y
    oChartDoc.HasLegend = False                                                                  ' Carece de leyenda
    '----------------------------------------------------------------------------
    ' 17º Describimos las series de datos
   
    oChartDoc.Data.setColumnDescriptions(ColumnArray())                                          ' Datos recogidos en el array del paso nº 5
    oEjeZ = oDiagram.getZAxis                                                                    ' Controlamos el eje Z 
    oEjeZ.CharHeight=7                                                                           ' Tamaño de la letra 
    oEjeZ.TextRotation = 0                                                                       ' Sin rotación
    '------------------------------------------------------------------------------
    ' 18º Describimos las columnas
    
    oChartDoc.Data.setRowDescriptions(RowArray())                                                ' Datos recogidos en el array del paso nº6
    oEjeX = oDiagram.getXAxis                                                                    ' Controlamos el eje  X
    oEjeX.CharHeight=7                                                                           ' Tamaño de la letra
    oEjeX.TextRotation = 9000                                                                    ' Giro de 90 grados 
   
    oEjeY = oDiagram.getYAxis                                                                    ' Controlamos el eje Y
    oEjeY.CharHeight=7                                                                           ' Tamaño de la letra
    oEjeY.TextRotation = 0                                                                       ' Sin rotación
    '--------------------------------------------------------------------------------
    ' 19º Tamaño del gráfico
   
    oEmbeded.width = 16000                                                                       ' Anchura del objeto embebido (gráfico)
    oEmbeded.Height= 8500                                                                       ' Altura del objeto embebido
    oEmbeded.HoriOrient =2                                                                       ' Centrado
    oEmbeded.AnchorType = com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH                   ' Anclaje al párrafo  
    oEmbeded.Surround = com.sun.star.text.WrapTextMode.DYNAMIC                               ' NONE, DYNAMIC, PARALLEL, LEFT, RIGHT

    '---------------------------------------------------------------------------------------
    ' 20º Añadimos párrafo al final
    
    oText.InsertControlCharacter(oText.getEnd(),com.sun.star.text.ControlCharacter.APPEND_PARAGRAPH, False)
    '-------------------------------------------------------------------------------------------  
    ' 21ºAñadimos una línea de texto
    
     oCurs.gotoEnd(False)                                                                        ' Colocamos el cursor de texto al final del informe    
     oText.insertString(oCurs,CHR$(13) & "Al fín terminé.....", False)                           ' Colocamos un final triunfante.


End Sub 
.

If you want not to have the table, only the chart, you can start with a report based in whatever table you have. It doesn't mater. Then, at the end of the macro you can add "oTexttable.Dispose", and it will dissapear. So you have only the chart. Is the same if you call an empty writer document and then paste the chart ( you have not a texttable as reference, and you have to use "ThisComponent", instead "oreportdoc", and some changes more, but actually, I think it should be very similar.( I've never tried it before).
Sorry if my explanations are not very clear....

Bye!
Last edited by longi on Mon Sep 21, 2015 2:00 pm, edited 1 time in total.
OpenOffice 4.1.5 on Windows 10
LibreOffice 5.1 on Windows 7
LibreOffice 6.0.1 on Windows10
Nocton
Volunteer
Posts: 533
Joined: Fri Nov 05, 2010 10:27 am
Location: UK

Re: Issues with Reporting and adding charts

Post by Nocton »

Thank you. That is clearer.
I remember now that since OO 3.4, the problem has not been that one cannot create charts within the report, but that they then do not print - one gets a "Failed to parse the report error". I 'solved' the problem by creating a separate chart report using Calc. Although your solution is ingenious, I think that using Calc is easier unless it is absolutely essential to have the chart and the report on the same page.

Regards,

Nocton
OpenOffice 4.1.12 on Windows 10
Post Reply