我正在研究通过UNO与OpenOffice(swriter)进行交互的Java API。
对于TextTable,我很难设置TableColumn的“ OptimalWidth”属性。

我已经尝试了以下代码,似乎getColumns()方法无法将我带到TableColumn的属性,而只能插入和删除列。

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));
    }
}


谁能帮我或给我一些技巧来设置表格的OptimalWidth属性?
提前非常感谢您!

最佳答案

找出这是一段艰难的旅程,但我最终设法创建了一个功能完全符合此要求的功能:

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);
}


重要的是,dispatchHelper来自OpenOffice上下文,而不是当前文档。我通过这种方式检索dispatchHelper:

  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);

08-03 13:00