1. 首先要得到远程office组件的上下文.通过:
com.sun.star.uno.XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
得到,如果OpenOffice安装路径不是在工程的路径下面(我自己猜的), 就会报:
com.sun.star.comp.helper.BootstrapException: no office executable found!
解决办法可以参考http://blog.csdn.net/xt_chaoji/article/details/6617330
2. 得到 XMultiComponentFactory (ComponentFactory 工厂)
com.sun.star.lang.XMultiComponentFactory xMCF = xContext.getServiceManager();
3. 得到各种组件可以通过下面代码:
// docType 是 与 soffice 同目录下面的OpenOffice的其他shell文件,swrite等等
protected XComponent newDocComponent(String docType)
throws java.lang.Exception {
String loadUrl = "private:factory/" + docType;
mxRemoteServiceManager = this.getRemoteServiceManager();
Object desktop = mxRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", mxRemoteContext);
XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime
.queryInterface(XComponentLoader.class, desktop);
PropertyValue[] loadProps = new PropertyValue[0];
return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0,
loadProps);
}
4.得到 XTextDocument
XComponent xEmptyWriterComponent = newDocComponent("swriter");
XTextDocument mxDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,
xEmptyWriterComponent);
5. 得到一个文档的引用
XText mxDocText = mxDoc.getText();
6. 得到文档的属性列表
XPropertySet mxDocProps = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, mxDoc);
7. 建立光标,用来插入新的内容。
XTextCursor mxDocCursor = mxDocText.createTextCursor();
XSentenceCursor xSentenceCursor = (XSentenceCursor) UnoRuntime
.queryInterface(XSentenceCursor.class, mxDocCursor);
XWordCursor xWordCursor = (XWordCursor) UnoRuntime.queryInterface(
XWordCursor.class, mxDocCursor);
8.得到光标属性列表
XPropertySet xCursorProps = (XPropertySet) UnoRuntime .queryInterface(XPropertySet.class, mxDocCursor);
9.设置插入文字格式
xCursorProps.setPropertyValue("CharFontName", "宋体");
xCursorProps.setPropertyValue("CharWeight", new Float(FontWeight.BOLD));
xCursorProps.setPropertyValue("CharHeight", new Float(10.5));
// 居中显示
xCursorProps.setPropertyValue("ParaAdjust", com.sun.star.style.ParagraphAdjust.CENTER);
10.在该光标处插入信息
mxDocText.insertString(xSentenceCursor, “Hello World", true);
11. 保存的关键代码
protected void storeDocComponent(XComponent xDoc, String storeUrl)
throws java.lang.Exception {
XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
XStorable.class, xDoc);
PropertyValue[] storeProps = new PropertyValue[1];
storeProps[0] = new PropertyValue();
storeProps[0].Name = "FilterName";
storeProps[0].Value = "MS Word 97";
openOfficeJavaLogger.debug("... store \"" + xDoc.toString() + "\" to \"" + storeUrl
+ "\".");
xStorable.storeAsURL(storeUrl, storeProps);
}