def copyTable(document, tableSource, tableDestination):
# document is of odf.opendocument
# tableSource is a string with the name of the source table
# tableDestination is a string with the name of the destination table
# get all tables in document
allTables = document.getElementsByType(table.Table)
templateTable = None
for xTable in allTables:
if hasattr(xTable, 'attributes'):
tableName = xTable.getAttribute('name')
if tableName == tableSource:
templateTable = xTable
if templateTable is None:
print('Table not found')
return
# first need to know about the columns in the original table
cols = templateTable.getElementsByType(table.TableColumn)
# create a new table for the copy
copyTable = Table(name=tableDestination)
# run through all columns and create a new column in the destination table
# for each column in the source table
for itm in cols:
colNew = TableColumn()
# copy the stylename of the column (needed for columnwidth
colNew.setAttribute('stylename', itm.getAttribute('stylename') )
# add the created column to the destination table
copyTable.addElement(colNew)
# get all rows from the original table
rows = templateTable.getElementsByType(table.TableRow)
#run through all rows
for tempRow in rows:
# create a new roz
tr = TableRow()
# get all cells from the original table
cells = tempRow.getElementsByType(table.TableCell)
# run through all cells
for tempCell in cells:
# create a new cell
cell = TableCell()
# copy the attributes
cell.setAttribute('stylename', tempCell.getAttribute('stylename') )
cell.setAttribute('numbercolumnsspanned', tempCell.getAttribute('numbercolumnsspanned') )
cell.setAttribute('numbermatrixcolumnsspanned', tempCell.getAttribute('numbermatrixcolumnsspanned') )
# get all parapgraphs from the cell
paras = tempCell.getElementsByType(text.P)
for paraTemp in paras:
# extract the text
old_text = teletype.extractText(paraTemp)
# create a new paragraph
para_copy = P(text=old_text)
# append paragraph to the cell
cell.addElement(para_copy)
# add the cell to the row
tr.addElement(cell)
# append row to the destination table
copyTable.addElement(tr)
templateTable.parentNode.addElement(copyTable)
templateTable.parentNode.addElement(P() )