views:

425

answers:

2

I am working on Java API which interacts with OpenOffice(swriter) through UNO. For TextTable, I am having hard time setting TableColumn's "OptimalWidth" property.

I have tried the following code and it seems that getColumns() method cannot take me to TableColumn's property and let you only insert and remove columns.

XTableColumns xColumns = xTextTable.getColumns();
  XIndexAccess xIndexAccess = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class, xColumns);

  for (int i = 0; i < xIndexAccess.getCount(); i++) {
    XPropertySet xColumnProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, (Any) xIndexAccess.getByIndex(i));
    if (xColumnProps != null) {                
      xColumn.setPropertyValue("OptimalWidth", new Boolean(true));
    }
  }

Can anyone help me out or give me any tips setting OptimalWidth property for a table? Thank you very much in advance!

A: 

It was quite an odyssey to find out, but I finally managed to create a function which does exactly that:

private void optimizeTableColumnWidths(XTextTable table)
throws Exception
{
    XTextViewCursorSupplier cursorSupplier = (XTextViewCursorSupplier)
            UnoRuntime.queryInterface(XTextViewCursorSupplier.class,
                    document.getCurrentController());
    XTextViewCursor viewCursor = cursorSupplier.getViewCursor();

    String cellName = "A1";
    XText cellText = (XText)UnoRuntime.queryInterface(
            XText.class, table.getCellByName(cellName));
    XTextCursor cursor = cellText.createTextCursor();

    viewCursor.gotoRange(cursor, false);
    viewCursor.gotoEnd(true);
    viewCursor.gotoEnd(true);

    XController controller = document.getCurrentController();
    XFrame frame = controller.getFrame();
    XDispatchProvider dispatchProvider = (XDispatchProvider)
        UnoRuntime.queryInterface(XDispatchProvider.class, frame);

    String unoAction = ".uno:SetOptimalColumnWidth";
    String targetFrameName = "";
    int searchFlags = 0;
    PropertyValue[] properties = new PropertyValue[0];

    dispatchHelper.executeDispatch(
            dispatchProvider,
            unoAction,
            targetFrameName,
            searchFlags,
            properties);
}

It is important that the dispatchHelper comes from the OpenOffice context, and not from the current document. I retrieved the dispatchHelper this way:

  XComponentContext context = Bootstrap.bootstrap();
  XMultiComponentFactory factory =
        context.getServiceManager();
  Object dispatchHelperObject = factory.createInstanceWithContext(
        "com.sun.star.frame.DispatchHelper", ooContext);
  this.dispatchHelper = (XDispatchHelper)UnoRuntime.queryInterface(
        XDispatchHelper.class, dispatchHelperObject);
silwol
A: 

Thanks a lot silwol, it have been very helpful for me. In order to re-arrage the rows of the table we can use: ".uno:SetOptimalRowHeight" property.

Best Regards

Miguel