Example: Adding a New Spreadsheet

From Apache OpenOffice Wiki
Jump to: navigation, search



The following helper method opens a new spreadsheet document component. The method getRemoteServiceManager() retrieves a connection. Refer to chapter First Steps for additional information.

 import com.sun.star.lang.XComponent;
 import com.sun.star.frame.XComponentLoader;
 import com.sun.star.beans.PropertyValue;
 
 ...
 
 protected XComponent newSpreadsheetComponent() throws java.lang.Exception {
     String loadUrl = "private:factory/scalc";
     xRemoteServiceManager = this.getRemoteServiceManager(unoUrl);
     Object desktop = xRemoteServiceManager.createInstanceWithContext(
         "com.sun.star.frame.Desktop", xRemoteContext);
     XComponentLoader xComponentLoader = (XComponentLoader)UnoRuntime.queryInterface(
         XComponentLoader.class, desktop);
     PropertyValue[] loadProps = new PropertyValue[0];
     return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0, loadProps); 
 }

Our helper returns a com.sun.star.lang.XComponent interface for the recently loaded document. Now the XComponent is passed to the following method insertSpreadsheet() to add a new spreadsheet to our document.

 import com.sun.star.sheet.XSpreadsheetDocument;
 import com.sun.star.sheet.XSpreadsheet; 
 
 ...
 
 /** Inserts a new empty spreadsheet with the specified name.
     @param xSheetComponent The XComponent interface of a loaded document object
     @param aName The name of the new sheet.
     @param nIndex The insertion index.
     @return The XSpreadsheet interface of the new sheet.
  */
 public XSpreadsheet insertSpreadsheet(XComponent xSheetComponent, String aName, short nIndex) {
     XSpreadsheetDocument xDocument = (XSpreadsheetDocument)UnoRuntime.queryInterface(
         XSpreadsheetDocument.class, xSheetComponent);
 
     // Collection of sheets
     com.sun.star.sheet.XSpreadsheets xSheets = xDocument.getSheets();
     com.sun.star.sheet.XSpreadsheet xSheet = null;
     
     try {
         xSheets.insertNewByName(aName, nIndex);
         xSheet = (com.sun.star.sheet.XSpreadsheet) UnoRuntime.queryInterface(
             com.sun.star.sheet.XSpreadsheet.class, xSheets.getByName(aName));
     } catch (Exception ex) {
     }
   
     return xSheet;
 }
Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages