bump product version to 4.1.6.2
[LibreOffice.git] / odk / examples / DevelopersGuide / Spreadsheet / SpreadsheetDocHelper.java
blob58dbf4873d64c92271e0de5b2b3ede5f2a590fb1
1 /*************************************************************************
3 * The Contents of this file are made available subject to the terms of
4 * the BSD license.
6 * Copyright 2000, 2010 Oracle and/or its affiliates.
7 * All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of Sun Microsystems, Inc. nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
28 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
30 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
31 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 *************************************************************************/
35 import com.sun.star.frame.XComponentLoader;
36 import com.sun.star.lang.XComponent;
38 import com.sun.star.uno.UnoRuntime;
39 import com.sun.star.uno.RuntimeException;
41 // __________ implementation ____________________________________
43 /** This is a helper class for the spreadsheet and table samples.
44 It connects to a running office and creates a spreadsheet document.
45 Additionally it contains various helper functions.
47 public class SpreadsheetDocHelper
50 // __ private members ___________________________________________
52 private final String msDataSheetName = "Data";
54 private com.sun.star.uno.XComponentContext mxRemoteContext;
55 private com.sun.star.lang.XMultiComponentFactory mxRemoteServiceManager;
56 // private com.sun.star.lang.XMultiServiceFactory mxMSFactory;
57 private com.sun.star.sheet.XSpreadsheetDocument mxDocument;
59 // ________________________________________________________________
61 public SpreadsheetDocHelper( String[] args )
63 // Connect to a running office and get the service manager
64 connect();
66 // Create a new spreadsheet document
67 try
69 mxDocument = initDocument();
71 catch (Exception ex)
73 System.err.println( "Couldn't create document: " + ex );
74 System.err.println( "Error: Couldn't create Document\nException Message = "
75 + ex.getMessage());
76 ex.printStackTrace();
77 System.exit( 1 );
81 // __ helper methods ____________________________________________
83 /** Returns the service manager of the connected office.
84 @return XMultiComponentFactory interface of the service manager. */
85 public com.sun.star.lang.XMultiComponentFactory getServiceManager()
87 return mxRemoteServiceManager;
90 /** Returns the component context of the connected office
91 @return XComponentContext interface of the context. */
92 public com.sun.star.uno.XComponentContext getContext()
94 return mxRemoteContext;
97 /** Returns the whole spreadsheet document.
98 @return XSpreadsheetDocument interface of the document. */
99 public com.sun.star.sheet.XSpreadsheetDocument getDocument()
101 return mxDocument;
104 /** Returns the spreadsheet with the specified index (0-based).
105 @param nIndex The index of the sheet.
106 @return XSpreadsheet interface of the sheet. */
107 public com.sun.star.sheet.XSpreadsheet getSpreadsheet( int nIndex )
109 // Collection of sheets
110 com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets();
111 com.sun.star.sheet.XSpreadsheet xSheet = null;
114 com.sun.star.container.XIndexAccess xSheetsIA =
115 UnoRuntime.queryInterface(
116 com.sun.star.container.XIndexAccess.class, xSheets );
117 xSheet = UnoRuntime.queryInterface(
118 com.sun.star.sheet.XSpreadsheet.class, xSheetsIA.getByIndex(nIndex));
120 catch (Exception ex)
122 System.err.println( "Error: caught exception in getSpreadsheet()!\nException Message = "
123 + ex.getMessage());
124 ex.printStackTrace();
126 return xSheet;
129 /** Inserts a new empty spreadsheet with the specified name.
130 @param aName The name of the new sheet.
131 @param nIndex The insertion index.
132 @return The XSpreadsheet interface of the new sheet. */
133 public com.sun.star.sheet.XSpreadsheet insertSpreadsheet(
134 String aName, short nIndex )
136 // Collection of sheets
137 com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets();
138 com.sun.star.sheet.XSpreadsheet xSheet = null;
141 xSheets.insertNewByName( aName, nIndex );
142 xSheet = UnoRuntime.queryInterface(com.sun.star.sheet.XSpreadsheet.class,
143 xSheets.getByName( aName ));
145 catch (Exception ex)
147 System.err.println( "Error: caught exception in insertSpreadsheet()!\nException Message = "
148 + ex.getMessage());
149 ex.printStackTrace();
151 return xSheet;
154 // ________________________________________________________________
155 // Methods to fill values into cells.
157 /** Writes a double value into a spreadsheet.
158 @param xSheet The XSpreadsheet interface of the spreadsheet.
159 @param aCellName The address of the cell (or a named range).
160 @param fValue The value to write into the cell. */
161 public void setValue(
162 com.sun.star.sheet.XSpreadsheet xSheet,
163 String aCellName,
164 double fValue ) throws RuntimeException, Exception
166 xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ).setValue( fValue );
169 /** Writes a formula into a spreadsheet.
170 @param xSheet The XSpreadsheet interface of the spreadsheet.
171 @param aCellName The address of the cell (or a named range).
172 @param aFormula The formula to write into the cell. */
173 public void setFormula(
174 com.sun.star.sheet.XSpreadsheet xSheet,
175 String aCellName,
176 String aFormula ) throws RuntimeException, Exception
178 xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ).setFormula( aFormula );
181 /** Writes a date with standard date format into a spreadsheet.
182 @param xSheet The XSpreadsheet interface of the spreadsheet.
183 @param aCellName The address of the cell (or a named range).
184 @param nDay The day of the date.
185 @param nMonth The month of the date.
186 @param nYear The year of the date. */
187 public void setDate(
188 com.sun.star.sheet.XSpreadsheet xSheet,
189 String aCellName,
190 int nDay, int nMonth, int nYear ) throws RuntimeException, Exception
192 // Set the date value.
193 com.sun.star.table.XCell xCell = xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 );
194 String aDateStr = nMonth + "/" + nDay + "/" + nYear;
195 xCell.setFormula( aDateStr );
197 // Set standard date format.
198 com.sun.star.util.XNumberFormatsSupplier xFormatsSupplier =
199 UnoRuntime.queryInterface(
200 com.sun.star.util.XNumberFormatsSupplier.class, getDocument() );
201 com.sun.star.util.XNumberFormatTypes xFormatTypes =
202 UnoRuntime.queryInterface(
203 com.sun.star.util.XNumberFormatTypes.class, xFormatsSupplier.getNumberFormats() );
204 int nFormat = xFormatTypes.getStandardFormat(
205 com.sun.star.util.NumberFormat.DATE, new com.sun.star.lang.Locale() );
207 com.sun.star.beans.XPropertySet xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCell );
208 xPropSet.setPropertyValue( "NumberFormat", new Integer( nFormat ) );
211 /** Draws a colored border around the range and writes the headline in the
212 first cell.
213 @param xSheet The XSpreadsheet interface of the spreadsheet.
214 @param aRange The address of the cell range (or a named range).
215 @param aHeadline The headline text. */
216 public void prepareRange(
217 com.sun.star.sheet.XSpreadsheet xSheet,
218 String aRange, String aHeadline ) throws RuntimeException, Exception
220 com.sun.star.beans.XPropertySet xPropSet = null;
221 com.sun.star.table.XCellRange xCellRange = null;
223 // draw border
224 xCellRange = xSheet.getCellRangeByName( aRange );
225 xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange );
226 com.sun.star.table.BorderLine aLine = new com.sun.star.table.BorderLine();
227 aLine.Color = 0x99CCFF;
228 aLine.InnerLineWidth = aLine.LineDistance = 0;
229 aLine.OuterLineWidth = 100;
230 com.sun.star.table.TableBorder aBorder = new com.sun.star.table.TableBorder();
231 aBorder.TopLine = aBorder.BottomLine = aBorder.LeftLine = aBorder.RightLine = aLine;
232 aBorder.IsTopLineValid = aBorder.IsBottomLineValid = true;
233 aBorder.IsLeftLineValid = aBorder.IsRightLineValid = true;
234 xPropSet.setPropertyValue( "TableBorder", aBorder );
236 // draw headline
237 com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange );
238 com.sun.star.table.CellRangeAddress aAddr = xAddr.getRangeAddress();
240 xCellRange = xSheet.getCellRangeByPosition(
241 aAddr.StartColumn, aAddr.StartRow, aAddr.EndColumn, aAddr.StartRow );
242 xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange );
243 xPropSet.setPropertyValue( "CellBackColor", new Integer( 0x99CCFF ) );
244 // write headline
245 com.sun.star.table.XCell xCell = xCellRange.getCellByPosition( 0, 0 );
246 xCell.setFormula( aHeadline );
247 xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCell );
248 xPropSet.setPropertyValue( "CharColor", new Integer( 0x003399 ) );
249 xPropSet.setPropertyValue( "CharWeight", new Float( com.sun.star.awt.FontWeight.BOLD ) );
252 // ________________________________________________________________
253 // Methods to create cell addresses and range addresses.
255 /** Creates a com.sun.star.table.CellAddress and initializes it
256 with the given range.
257 @param xSheet The XSpreadsheet interface of the spreadsheet.
258 @param aCell The address of the cell (or a named cell). */
259 public com.sun.star.table.CellAddress createCellAddress(
260 com.sun.star.sheet.XSpreadsheet xSheet,
261 String aCell ) throws RuntimeException, Exception
263 com.sun.star.sheet.XCellAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellAddressable.class,
264 xSheet.getCellRangeByName( aCell ).getCellByPosition( 0, 0 ) );
265 return xAddr.getCellAddress();
268 /** Creates a com.sun.star.table.CellRangeAddress and initializes
269 it with the given range.
270 @param xSheet The XSpreadsheet interface of the spreadsheet.
271 @param aRange The address of the cell range (or a named range). */
272 public com.sun.star.table.CellRangeAddress createCellRangeAddress(
273 com.sun.star.sheet.XSpreadsheet xSheet, String aRange )
275 com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class,
276 xSheet.getCellRangeByName( aRange ) );
277 return xAddr.getRangeAddress();
280 // ________________________________________________________________
281 // Methods to convert cell addresses and range addresses to strings.
283 /** Returns the text address of the cell.
284 @param nColumn The column index.
285 @param nRow The row index.
286 @return A string containing the cell address. */
287 public String getCellAddressString( int nColumn, int nRow )
289 String aStr = "";
290 if (nColumn > 25)
291 aStr += (char) ('A' + nColumn / 26 - 1);
292 aStr += (char) ('A' + nColumn % 26);
293 aStr += (nRow + 1);
294 return aStr;
297 /** Returns the text address of the cell range.
298 @param aCellRange The cell range address.
299 @return A string containing the cell range address. */
300 public String getCellRangeAddressString(
301 com.sun.star.table.CellRangeAddress aCellRange )
303 return
304 getCellAddressString( aCellRange.StartColumn, aCellRange.StartRow )
305 + ":"
306 + getCellAddressString( aCellRange.EndColumn, aCellRange.EndRow );
309 /** Returns the text address of the cell range.
310 @param xCellRange The XSheetCellRange interface of the cell range.
311 @param bWithSheet true = Include sheet name.
312 @return A string containing the cell range address. */
313 public String getCellRangeAddressString(
314 com.sun.star.sheet.XSheetCellRange xCellRange,
315 boolean bWithSheet )
317 String aStr = "";
318 if (bWithSheet)
320 com.sun.star.sheet.XSpreadsheet xSheet = xCellRange.getSpreadsheet();
321 com.sun.star.container.XNamed xNamed = UnoRuntime.queryInterface( com.sun.star.container.XNamed.class, xSheet );
322 aStr += xNamed.getName() + ".";
324 com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange );
325 aStr += getCellRangeAddressString( xAddr.getRangeAddress() );
326 return aStr;
329 /** Returns a list of addresses of all cell ranges contained in the collection.
330 @param xRangesIA The XIndexAccess interface of the collection.
331 @return A string containing the cell range address list. */
332 public String getCellRangeListString(
333 com.sun.star.container.XIndexAccess xRangesIA ) throws RuntimeException, Exception
335 String aStr = "";
336 int nCount = xRangesIA.getCount();
337 for (int nIndex = 0; nIndex < nCount; ++nIndex)
339 if (nIndex > 0)
340 aStr += " ";
341 Object aRangeObj = xRangesIA.getByIndex( nIndex );
342 com.sun.star.sheet.XSheetCellRange xCellRange = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetCellRange.class, aRangeObj );
343 aStr += getCellRangeAddressString( xCellRange, false );
345 return aStr;
348 // ________________________________________________________________
350 // Connect to a running office that is accepting connections.
351 private void connect()
353 if (mxRemoteContext == null && mxRemoteServiceManager == null) {
354 try {
355 // First step: get the remote office component context
356 mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
357 System.out.println("Connected to a running office ...");
359 mxRemoteServiceManager = mxRemoteContext.getServiceManager();
361 catch( Exception e) {
362 System.err.println("ERROR: can't get a component context from a running office ...");
363 e.printStackTrace();
364 System.exit(1);
369 /** Creates an empty spreadsheet document.
370 @return The XSpreadsheetDocument interface of the document. */
371 private com.sun.star.sheet.XSpreadsheetDocument initDocument()
372 throws RuntimeException, Exception
374 XComponentLoader aLoader = UnoRuntime.queryInterface(
375 XComponentLoader.class,
376 mxRemoteServiceManager.createInstanceWithContext(
377 "com.sun.star.frame.Desktop", mxRemoteContext));
379 XComponent xComponent = aLoader.loadComponentFromURL(
380 "private:factory/scalc", "_blank", 0,
381 new com.sun.star.beans.PropertyValue[0] );
383 return UnoRuntime.queryInterface(
384 com.sun.star.sheet.XSpreadsheetDocument.class, xComponent );
387 // ________________________________________________________________