Search code examples
pythonpython-2.7ods

add a sheet to an ods file via python


I started with the package simpleodspy

and it worked fine until I wanted to add an new sheet to an ods file.

Than I figured out that simpleodspy is just an better wrapper for odfpy to simpliy the api. So I guess they scipted the adding an sheet part.

So I tried to figure out how to do it with odfpy.

But I stucked.

So does someone know if it is possible to add an sheet to ods files?

If yes how ?


Solution

  • Here's the sample code to add a new sheet:

    from odf.opendocument import load
    from odf.table import Table
    from odf.table import TableCell
    from odf.table import TableRow
    from odf.text import P
    
    #loading it
    book = load('your.ods')
    #create a new sheet in memory
    sheet = Table(name="test sheet")
    #create a new row
    tablerow=TableRow()
    #create a new cell
    cell=TableCell()
    #fill-in a cell
    cell.addElement(P(text="hello world"))
    #add a cell to the row
    tablerow.addElement(cell)
    #add the row to the sheet
    sheet.addElement(tablerow)
    #adding the new to the book
    book.spreadsheet.addElement(sheet)
    #save it
    book.save('your_new.ods')