Search code examples
javapythonlibreofficeopenoffice.orguno

How to clone a TextTable and paste N cloned TextTable below the original TextTable using open office uno API


I have a XTextTable instance. How can I 1) clone the text table (both content and format) into a new XTextTable instance and 2) insert the new instance below the text table using insertTextContent method?

Part of the code is like this

if (element.supportsService("com.sun.star.text.TextTable")):
  table = element
  tableTemplate = doc.createInstance("com.sun.star.text.TextTable")
  #clone properties and content of table to tableTemplate
  #get the position of insertion RANGE
  for datum in data:
     doc.getText().insertTextContent(RANGE,childTable,False)
     #replace placeholder with datum

The code is in python but I can also translate from Java


Solution

  • It seems to me that you have chosen not the easiest way to solve the problem - creating a new object and cloning its properties is a rather laborious process. If you need exact copies of your table, try this algorithm:

    Sub CloneTable
    Dim oTable As Variant       ' Your object
    Dim oCurrentController As Variant   ' Controller will copy-paste content
    Dim oViewCursor As Variant  ' Cursor will select some points in document
    Dim oTransferable As Variant    ' "Clipboard"
    
        oTable = ThisComponent.getTextTables().getByName("Table1")  ' Get your object as you can
        oCurrentController = ThisComponent.getCurrentController()   ' Create (get) two important tools
        oViewCursor = oCurrentController.getViewCursor()
        oCurrentController.select(oTable)   ' Move your cursor to the beginning of the first cell of your table
        oViewCursor.goLeft(1,False) ' Move the cursor to the left (no selection), position it right before the table
        oViewCursor.goRight(1,True) ' Move the cursor to the right (this time with a selection), select your entire table
        oTransferable = oCurrentController.getTransferable()    ' Get all the information about a selected part of document
        oViewCursor.goRight(0,False)        ' Remove the selection from the table 
    Rem (otherwise the first insert will simply overwrite the existing object and you will end up with one less table than expected)
        For i = 1 to 10 ' Repeat the required number of times
            oCurrentController.insertTransferable(oTransferable) ' Paste an exact copy of the object at the current cursor position
        Next i
    End Sub