Search code examples
javalibreofficeuno

Insert new row into LibreOffice writer table using UNO


I have recently tried to code a small java file which will insert a row into an already existing table in a .odt document. The table itself has 4 rows and 3 column, but I would like to implement a check which will expand that table if the content to be inserted is larger than 4. However, every time I try to get the table's rows, it returns a null pointer. I am not that familiar with UNO api, but as far as i read through the documentation, the class XColumnsAndRowRange should be used in this situation. My code is as follows:

XTextTablesSupplier xTablesSupplier = (XTextTablesSupplier) UnoRuntime.queryInterface(XTextTablesSupplier.class, xTextDocument);

    XNameAccess xNamedTables = xTablesSupplier.getTextTables();
    try {
        Object table = xNamedTables.getByName(tblName);
        XTextTable xTable = (XTextTable) UnoRuntime.queryInterface(XTextTable.class, table);
        XCellRange xCellRange = (XCellRange) UnoRuntime.queryInterface(XCellRange.class, table);
        if(flag){
            XColumnRowRange xCollumnAndRowRange =(XColumnRowRange) 
                    UnoRuntime.queryInterface(XColumnRowRange.class, xCellRange);
                XTableRows rows = xCollumnAndRowRange.getRows();

                 System.out.println("Testing if this works");
                rows.insertByIndex(4, size-4);
        }

I am not sure if I am missing something here or if I should be using a different function.


Solution

  • As Lyrl suggested, this works:

    XTableRows rows = xTable.getRows();
    

    Apparently XColumnRowRange is only used for spreadsheets.

    Note: With Basic or Python you would not have this problem, because those languages do not need queryInterface. The code would simply be:

    table = tables.getByName(tblName)
    rows = table.getRows()