找出来是一段艰辛的旅程,但我终于设法创建了一个函数,它可以做到这一点:
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);