Jump to content

Comment gérer les bordures d'un tableau ?

From The Document Foundation Wiki
This page is a translated version of the page Macros/Writer/003 and the translation is 47% complete.
Outdated translations are marked like this.


Description

On souhaite gérer par programme la définition des bordures d'un tableau ou d'une cellule.

Note: it might be more efficient to manipulate borders using styles, see https://ask.libreoffice.org/t/how-to-set-textframe-borders-at-once/108826

Les bordures sont accessibles via la propriété com.sun.star.table.TableBorder[1].

Les éléments de cette structure sont de deux types :

  • Des bordures (haut, bas, gauche, droite, horizontale, verticale) ; les bordures sont des structures com.sun.star.table.BorderLine2[2] qui "ajoutent" les éléments de style[3] à la structure com.sun.star.table.BorderLine[4].
  • Des booléens (IsLeftLineValid, IsRightLineValid, IsTopLineValid, etc.). En écriture, les définir à True pour modifier la ligne correspondante et à False pour l'ignorer, autrement dit pour garder sa valeur actuelle.

La définition de l'espacement avec le contenu se fait via la propriété com.sun.star.table.TableBorderDistances[5] de la table. Là encore il s'agit d'une structure bâtie selon le même principe : BottomDistance, LeftDistance, etc. et des booléens pour gérer la modification ou non.

La procédure suivante s'applique au tableau courant :

  • On commence par tester que le curseur figure bien dans un tableau.
  • L'objectif est de remplacer les bordures actuelles (les paramètres Is... sont définis à True) pour obtenir un encadrement extérieur et des lignes horizontales doubles. En revanche on ne veut pas de lignes verticales. Il faut en conséquence .IsVerticalLineValid = true et VerticalLine = LibONoLine, une structure définie pour appliquer une ligne "vide". On ne peut simplement utiliser .IsVerticalLineValid = false car le tableau courant peut avoir des lignes verticales définies et on désire les supprimer. Avec le paramètre false les lignes existantes seraient laissées dans leur état actuel.
  • L'espacement avec le contenu désiré est 0,30cm.
  • Le paramètre Fusionner les styles de ligne adjacents se définit par la propriété CollapsingBorders de la table.

Code

En LibreOffice Basic:

Option Explicit


Sub Main()
    '''Choisissez laquelle des deux sous-routines vous voulez appeler, en commentant celle que vous ne voulez pas.'''

    'EncadrerTableCourante
    <span class="mw-translate-fuzzy">EncadrerCell</span>("Tableau1","B2")

End Sub ' Main


Sub EncadrerTableCourante()
    ''' <span lang="en" dir="ltr" class="mw-content-ltr">Add double-borders to all cells in the currently selected table</span>'''

    Dim oCursor As Object
    Dim oTable As Object
    Dim oTableBorder As Object

    Dim oLine As New com.sun.star.table.BorderLine2
    Dim oNoLine As New com.sun.star.table.BorderLine2
    Dim oBorderDistances As New com.sun.star.table.TableBorderDistances
    oCursor = ThisComponent.CurrentController.ViewCursor

    If (isEmpty(oCursor.textTable)) Then
        MsgBox "Le curseur n'est pas dans un tableau", _
            MB_ICONINFORMATION, _
            "Mise en forme du tableau"
    Else
        With oLine
            .Color = 0
            .InnerLineWidth = 10
            .LineDistance = 60 
            .LineStyle = com.sun.star.table.BorderLineStyle.DOUBLE 
            .LineWidth = 5
            .OuterLineWidth = 10
        End With
        With oNoLine
            .Color = 0
            .InnerLineWidth = 0
            .LineDistance = 0
            .LineStyle = 0
            .LineWidth = 0
            .OuterLineWidth = 0
        End With
        With oBorderDistances
            .BottomDistance = 300
            .IsBottomDistanceValid = True   
            .IsLeftDistanceValid = True   
            .IsRightDistanceValid = True   
            .IsTopDistanceValid = True   
            .LeftDistance = 300   
            .RightDistance = 300
            .TopDistance = 300
        End With
        
        oTable = oCursor.TextTable
        oTableBorder = oTable.TableBorder
        
        With oTableBorder        
            .IsLeftLineValid = true
            .IsRightLineValid = true
            .IsTopLineValid = true
            .IsBottomLineValid = true
            .IsHorizontalLineValid = true
            .IsVerticalLineValid = true
            .LeftLine = oLine
            .RightLine = oLine
            .TopLine = oLine
            .BottomLine = oLine 
            .HorizontalLine = oLine
            .VerticalLine = oNoLine
        End With
        
        With oTable
            .TableBorder = oTableBorder 
            .HoriOrient = com.sun.star.text.HoriOrientation.FULL 
            .CollapsingBorders = true
            .TableBorderDistances = oBorderDistances
        End With  

    End If

End Sub ' EncadrerTableCourante


Private Sub <span class="mw-translate-fuzzy">EncadrerCell</span>(myTable As String, myCell As String)
    ''''''Encadrer une cellule spécifique dans un tableau traits doubles, espacement 0.10cm''''''

    Dim oTable As Object
    Dim oCell As Object
    Dim oLine As New com.sun.star.table.BorderLine2

    With oLine
        .Color = 0
        .InnerLineWidth = 10
        .LineDistance = 60 
        .LineStyle = com.sun.star.table.BorderLineStyle.DOUBLE
        .LineWidth = 2
        .OuterLineWidth = 10
    End With

    oTable = ThisComponent.TextTables.getByName(myTable)
    oCell = oTable.getCellByName(myCell)

    With oCell
        .LeftBorder = oLine
        .LeftBorderDistance = 100
        .RightBorder = oLine
        .RightBorderDistance = 100
        .TopBorder = oLine
        .TopBorderDistance = 100
        .BottomBorder = oLine 
        .BottomBorderDistance = 100
    End With

End Sub ' EncadrerCell
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from com.sun.star.table import BorderLine2
from com.sun.star.table import TableBorderDistances
from com.sun.star.table.BorderLineStyle import DOUBLE
import uno
import msgbox
from com.sun.star.text.HoriOrientation import FULL

<div lang="en" dir="ltr" class="mw-content-ltr">
def _msgbox(prompt='', title='LibreOffice'):
    """ Displays a dialog box containing a message and returns a value."""
    mb = msgbox.MsgBox(uno.getComponentContext())
    mb.addButton('OK')
    mb.show(prompt, 0, title)
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
def AddBordersToAllCells():
    """Add double-borders to all cells in the currently selected table"""
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    view_cursor = model.getCurrentController()
    cursor = view_cursor.getViewCursor()
    line = BorderLine2()
    no_line = BorderLine2()
    border_distances = TableBorderDistances()
    if cursor.TextTable is None:
        _msgbox("The cursor is not inside a table.", "Warning from AddBordersToAllCells()")
    else:
        line.Color = 0
        line.InnerLineWidth = 10
        line.LineDistance = 60
        line.LineStyle = DOUBLE
        line.LineWidth = 5
        line.OuterLineWidth = 10
</div>

        <div lang="en" dir="ltr" class="mw-content-ltr">
no_line.Color = 0
        no_line.InnerLineWidth = 0
        no_line.LineDistance = 0
        no_line.LineStyle = 0
        no_line.LineWidth = 0
        no_line.OuterLineWidth = 0
</div>

        <div lang="en" dir="ltr" class="mw-content-ltr">
border_distances.BottomDistance = 300
        border_distances.IsBottomDistanceValid = True
        border_distances.IsLeftDistanceValid = True
        border_distances.IsRightDistanceValid = True
        border_distances.IsTopDistanceValid = True
        border_distances.LeftDistance = 300
        border_distances.RightDistance = 300
        border_distances.TopDistance = 300
</div>

        <div lang="en" dir="ltr" class="mw-content-ltr">
table = cursor.TextTable
        table_border = table.TableBorder
        table_border.IsLeftLineValid = True
        table_border.IsRightLineValid = True
        table_border.IsTopLineValid = True
        table_border.IsBottomLineValid = True
        table_border.IsHorizontalLineValid = True
        table_border.IsVerticalLineValid = True
        table_border.LeftLine = line
        table_border.RightLine = line
        table_border.TopLine = line
        table_border.BottomLine = line
        table_border.HorizontalLine = line
        table_border.VerticalLine = no_line
</div>

        <div lang="en" dir="ltr" class="mw-content-ltr">
table.TableBorder = table_border
        table.CollapsingBorders = True
        table.TableBorderDistances = border_distances
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
def Main():
    _AddBordersToCell("Table1", "B2")
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
def _AddBordersToCell(my_table, my_cell):
    """Add double-borders to specified cell in specified table"""
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
</div>

    <div lang="en" dir="ltr" class="mw-content-ltr">
line = BorderLine2()
    line.Color = 0
    line.InnerLineWidth = 10
    line.LineDistance = 60
    line.LineStyle = DOUBLE
    line.LineWidth = 2
    line.OuterLineWidth = 10
</div>

    <div lang="en" dir="ltr" class="mw-content-ltr">
table = model.TextTables.getByName(my_table)
    cell = table.getCellByName(my_cell)
</div>

    <div lang="en" dir="ltr" class="mw-content-ltr">
cell.LeftBorder = line
    cell.LeftBorderDistance = 100
    cell.RightBorder = line
    cell.RightBorderDistance = 100
    cell.TopBorder = line
    cell.TopBorderDistance = 100
    cell.BottomBorder = line
    cell.BottomBorderDistance = 100
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
g_exportedScripts = (AddBordersToAllCells, Main)
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">

Fichier ODT pour tester la macro

Notes