odfpy

How to create a Table in a OpenDocumentText document using odfpy


I would like to create a table in an odt (OpenDocumentText) file using odfpy?

The docu of the package is outdated and the project nearly orphaned (but maybe on its way back I think).

Be aware I don't mean Spreadsheet documents but text documents.


Solution

  • Note: The person who raised the question has already solved the problem and also shared a link for reference: Here
    Following code is the simplest way to create a table and add it to the document. Kindly ask in comments or raise new questions if you want more thing in this regards. (Actually I had to spend a lot of time to understand odfpy and now i want to share the knowledge. :D ):

    from odf import text, teletype, userfield, table
    from odf.table import Table, TableColumn, TableRow, TableCell
    from odf.style import Style, TableProperties, TableRowProperties, TableColumnProperties, TableCellProperties
    from odf.opendocument import load, OpenDocumentText
    
    dest_file = "test.odt"
    doc = OpenDocumentText()
    
    #table styling - Its like CSS in html
    table_style = Style(name="table-style", family="table")
    table_style.addElement(TableProperties(align="margins"))
    doc.automaticstyles.addElement(table_style)
    
    table_cell_style = Style(name="table-cell-style", family="table-cell")
    table_cell_style.addElement(TableCellProperties(border="0.05pt solid #000000"))
    doc.automaticstyles.addElement(table_cell_style)
    
    table_column_style = Style(name="table-column-style", family="table-column")
    table_column_style.addElement(TableColumnProperties(columnwidth="0.2in"))
    doc.automaticstyles.addElement(table_column_style)
    
    table_row_style = Style(name="table-row-style", family="table-row")
    table_row_style.addElement(TableRowProperties(useoptimalrowheight=False))
    doc.automaticstyles.addElement(table_row_style)
    #--styling ends here--
    
    # create table 
    doc_table = Table(name="xyz-table", stylename="table-style")
    # add 11 columns to the table
    table_column = TableColumn(numbercolumnsrepeated="11", stylename="table-column-style")
    doc_table.addElement(table_column)
    """
    #   or you can do the followig for the same as above
    for i in range(11):
        table_column = TableColumn(stylename="table-column-style")
        doc_table.addElement(table_column)
    """
    # add data of 10 rows in the table
    for i in range(10):
        table_row = TableRow()   
        doc_table.addElement(table_row)
        # PUT A TO K IN THE CELLS
        data = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K")
        for i in list(data):
            column_data = TableCell(valuetype="string", stylename="table-cell-style")
            table_row.addElement(column_data)
            column_data.addElement(text.P(text=i))
    doc.text.addElement(doc_table)
    doc.save(dest_file)
    #print(dir(doc))