Version 6.4.0.0.beta1, tag libreoffice-6.4.0.0.beta1
[LibreOffice.git] / odk / examples / DevelopersGuide / Spreadsheet / SpreadsheetDocHelper.java
blob0696a866cdc311cfa72e94f62978937fa41120bd
1 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*************************************************************************
4 * The Contents of this file are made available subject to the terms of
5 * the BSD license.
7 * Copyright 2000, 2010 Oracle and/or its affiliates.
8 * All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of Sun Microsystems, Inc. nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
29 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
31 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
32 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 *************************************************************************/
36 import com.sun.star.frame.XComponentLoader;
37 import com.sun.star.lang.XComponent;
39 import com.sun.star.uno.UnoRuntime;
40 import com.sun.star.uno.RuntimeException;
42 // __________ implementation ____________________________________
44 /** This is a helper class for the spreadsheet and table samples.
45 It connects to a running office and creates a spreadsheet document.
46 Additionally it contains various helper functions.
48 public class SpreadsheetDocHelper
51 // __ private members ___________________________________________
53 private com.sun.star.uno.XComponentContext mxRemoteContext;
54 private com.sun.star.lang.XMultiComponentFactory mxRemoteServiceManager;
55 private com.sun.star.sheet.XSpreadsheetDocument mxDocument;
59 public SpreadsheetDocHelper( String[] args )
61 // Connect to a running office and get the service manager
62 connect();
64 // Create a new spreadsheet document
65 try
67 mxDocument = initDocument();
69 catch (Exception ex)
71 System.err.println( "Couldn't create document: " + ex );
72 System.err.println( "Error: Couldn't create Document\nException Message = "
73 + ex.getMessage());
74 ex.printStackTrace();
75 System.exit( 1 );
79 // __ helper methods ____________________________________________
81 /** Returns the service manager of the connected office.
82 @return XMultiComponentFactory interface of the service manager. */
83 public com.sun.star.lang.XMultiComponentFactory getServiceManager()
85 return mxRemoteServiceManager;
88 /** Returns the component context of the connected office
89 @return XComponentContext interface of the context. */
90 public com.sun.star.uno.XComponentContext getContext()
92 return mxRemoteContext;
95 /** Returns the whole spreadsheet document.
96 @return XSpreadsheetDocument interface of the document. */
97 public com.sun.star.sheet.XSpreadsheetDocument getDocument()
99 return mxDocument;
102 /** Returns the spreadsheet with the specified index (0-based).
103 @param nIndex The index of the sheet.
104 @return XSpreadsheet interface of the sheet. */
105 public com.sun.star.sheet.XSpreadsheet getSpreadsheet( int nIndex )
107 // Collection of sheets
108 com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets();
109 com.sun.star.sheet.XSpreadsheet xSheet = null;
112 com.sun.star.container.XIndexAccess xSheetsIA =
113 UnoRuntime.queryInterface(
114 com.sun.star.container.XIndexAccess.class, xSheets );
115 xSheet = UnoRuntime.queryInterface(
116 com.sun.star.sheet.XSpreadsheet.class, xSheetsIA.getByIndex(nIndex));
118 catch (Exception ex)
120 System.err.println( "Error: caught exception in getSpreadsheet()!\nException Message = "
121 + ex.getMessage());
122 ex.printStackTrace();
124 return xSheet;
127 /** Inserts a new empty spreadsheet with the specified name.
128 @param aName The name of the new sheet.
129 @param nIndex The insertion index.
130 @return The XSpreadsheet interface of the new sheet. */
131 public com.sun.star.sheet.XSpreadsheet insertSpreadsheet(
132 String aName, short nIndex )
134 // Collection of sheets
135 com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets();
136 com.sun.star.sheet.XSpreadsheet xSheet = null;
139 xSheets.insertNewByName( aName, nIndex );
140 xSheet = UnoRuntime.queryInterface(com.sun.star.sheet.XSpreadsheet.class,
141 xSheets.getByName( aName ));
143 catch (Exception ex)
145 System.err.println( "Error: caught exception in insertSpreadsheet()!\nException Message = "
146 + ex.getMessage());
147 ex.printStackTrace();
149 return xSheet;
153 // Methods to fill values into cells.
155 /** Writes a double value into a spreadsheet.
156 @param xSheet The XSpreadsheet interface of the spreadsheet.
157 @param aCellName The address of the cell (or a named range).
158 @param fValue The value to write into the cell. */
159 public void setValue(
160 com.sun.star.sheet.XSpreadsheet xSheet,
161 String aCellName,
162 double fValue ) throws RuntimeException, Exception
164 xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ).setValue( fValue );
167 /** Writes a formula into a spreadsheet.
168 @param xSheet The XSpreadsheet interface of the spreadsheet.
169 @param aCellName The address of the cell (or a named range).
170 @param aFormula The formula to write into the cell. */
171 public void setFormula(
172 com.sun.star.sheet.XSpreadsheet xSheet,
173 String aCellName,
174 String aFormula ) throws RuntimeException, Exception
176 xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ).setFormula( aFormula );
179 /** Writes a date with standard date format into a spreadsheet.
180 @param xSheet The XSpreadsheet interface of the spreadsheet.
181 @param aCellName The address of the cell (or a named range).
182 @param nDay The day of the date.
183 @param nMonth The month of the date.
184 @param nYear The year of the date. */
185 public void setDate(
186 com.sun.star.sheet.XSpreadsheet xSheet,
187 String aCellName,
188 int nDay, int nMonth, int nYear ) throws RuntimeException, Exception
190 // Set the date value.
191 com.sun.star.table.XCell xCell = xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 );
192 String aDateStr = nMonth + "/" + nDay + "/" + nYear;
193 xCell.setFormula( aDateStr );
195 // Set standard date format.
196 com.sun.star.util.XNumberFormatsSupplier xFormatsSupplier =
197 UnoRuntime.queryInterface(
198 com.sun.star.util.XNumberFormatsSupplier.class, getDocument() );
199 com.sun.star.util.XNumberFormatTypes xFormatTypes =
200 UnoRuntime.queryInterface(
201 com.sun.star.util.XNumberFormatTypes.class, xFormatsSupplier.getNumberFormats() );
202 int nFormat = xFormatTypes.getStandardFormat(
203 com.sun.star.util.NumberFormat.DATE, new com.sun.star.lang.Locale() );
205 com.sun.star.beans.XPropertySet xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCell );
206 xPropSet.setPropertyValue( "NumberFormat", Integer.valueOf( nFormat ) );
209 /** Draws a colored border around the range and writes the headline in the
210 first cell.
211 @param xSheet The XSpreadsheet interface of the spreadsheet.
212 @param aRange The address of the cell range (or a named range).
213 @param aHeadline The headline text. */
214 public void prepareRange(
215 com.sun.star.sheet.XSpreadsheet xSheet,
216 String aRange, String aHeadline ) throws RuntimeException, Exception
218 com.sun.star.beans.XPropertySet xPropSet = null;
219 com.sun.star.table.XCellRange xCellRange = null;
221 // draw border
222 xCellRange = xSheet.getCellRangeByName( aRange );
223 xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange );
224 com.sun.star.table.BorderLine aLine = new com.sun.star.table.BorderLine();
225 aLine.Color = 0x99CCFF;
226 aLine.InnerLineWidth = aLine.LineDistance = 0;
227 aLine.OuterLineWidth = 100;
228 com.sun.star.table.TableBorder aBorder = new com.sun.star.table.TableBorder();
229 aBorder.TopLine = aBorder.BottomLine = aBorder.LeftLine = aBorder.RightLine = aLine;
230 aBorder.IsTopLineValid = aBorder.IsBottomLineValid = true;
231 aBorder.IsLeftLineValid = aBorder.IsRightLineValid = true;
232 xPropSet.setPropertyValue( "TableBorder", aBorder );
234 // draw headline
235 com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange );
236 com.sun.star.table.CellRangeAddress aAddr = xAddr.getRangeAddress();
238 xCellRange = xSheet.getCellRangeByPosition(
239 aAddr.StartColumn, aAddr.StartRow, aAddr.EndColumn, aAddr.StartRow );
240 xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange );
241 xPropSet.setPropertyValue( "CellBackColor", Integer.valueOf( 0x99CCFF ) );
242 // write headline
243 com.sun.star.table.XCell xCell = xCellRange.getCellByPosition( 0, 0 );
244 xCell.setFormula( aHeadline );
245 xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCell );
246 xPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0x003399 ) );
247 xPropSet.setPropertyValue( "CharWeight", new Float( com.sun.star.awt.FontWeight.BOLD ) );
251 // Methods to create cell addresses and range addresses.
253 /** Creates a com.sun.star.table.CellAddress and initializes it
254 with the given range.
255 @param xSheet The XSpreadsheet interface of the spreadsheet.
256 @param aCell The address of the cell (or a named cell). */
257 public com.sun.star.table.CellAddress createCellAddress(
258 com.sun.star.sheet.XSpreadsheet xSheet,
259 String aCell ) throws RuntimeException, Exception
261 com.sun.star.sheet.XCellAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellAddressable.class,
262 xSheet.getCellRangeByName( aCell ).getCellByPosition( 0, 0 ) );
263 return xAddr.getCellAddress();
266 /** Creates a com.sun.star.table.CellRangeAddress and initializes
267 it with the given range.
268 @param xSheet The XSpreadsheet interface of the spreadsheet.
269 @param aRange The address of the cell range (or a named range). */
270 public com.sun.star.table.CellRangeAddress createCellRangeAddress(
271 com.sun.star.sheet.XSpreadsheet xSheet, String aRange )
273 com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class,
274 xSheet.getCellRangeByName( aRange ) );
275 return xAddr.getRangeAddress();
279 // Methods to convert cell addresses and range addresses to strings.
281 /** Returns the text address of the cell.
282 @param nColumn The column index.
283 @param nRow The row index.
284 @return A string containing the cell address. */
285 public String getCellAddressString( int nColumn, int nRow )
287 String aStr = "";
288 if (nColumn > 25)
289 aStr += (char) ('A' + nColumn / 26 - 1);
290 aStr += (char) ('A' + nColumn % 26);
291 aStr += (nRow + 1);
292 return aStr;
295 /** Returns the text address of the cell range.
296 @param aCellRange The cell range address.
297 @return A string containing the cell range address. */
298 public String getCellRangeAddressString(
299 com.sun.star.table.CellRangeAddress aCellRange )
301 return
302 getCellAddressString( aCellRange.StartColumn, aCellRange.StartRow )
303 + ":"
304 + getCellAddressString( aCellRange.EndColumn, aCellRange.EndRow );
307 /** Returns the text address of the cell range.
308 @param xCellRange The XSheetCellRange interface of the cell range.
309 @param bWithSheet true = Include sheet name.
310 @return A string containing the cell range address. */
311 public String getCellRangeAddressString(
312 com.sun.star.sheet.XSheetCellRange xCellRange,
313 boolean bWithSheet )
315 String aStr = "";
316 if (bWithSheet)
318 com.sun.star.sheet.XSpreadsheet xSheet = xCellRange.getSpreadsheet();
319 com.sun.star.container.XNamed xNamed = UnoRuntime.queryInterface( com.sun.star.container.XNamed.class, xSheet );
320 aStr += xNamed.getName() + ".";
322 com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange );
323 aStr += getCellRangeAddressString( xAddr.getRangeAddress() );
324 return aStr;
327 /** Returns a list of addresses of all cell ranges contained in the collection.
328 @param xRangesIA The XIndexAccess interface of the collection.
329 @return A string containing the cell range address list. */
330 public String getCellRangeListString(
331 com.sun.star.container.XIndexAccess xRangesIA ) throws RuntimeException, Exception
333 String aStr = "";
334 int nCount = xRangesIA.getCount();
335 for (int nIndex = 0; nIndex < nCount; ++nIndex)
337 if (nIndex > 0)
338 aStr += " ";
339 Object aRangeObj = xRangesIA.getByIndex( nIndex );
340 com.sun.star.sheet.XSheetCellRange xCellRange = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetCellRange.class, aRangeObj );
341 aStr += getCellRangeAddressString( xCellRange, false );
343 return aStr;
348 // Connect to a running office that is accepting connections.
349 private void connect()
351 if (mxRemoteContext == null && mxRemoteServiceManager == null) {
352 try {
353 // First step: get the remote office component context
354 mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
355 System.out.println("Connected to a running office ...");
357 mxRemoteServiceManager = mxRemoteContext.getServiceManager();
359 catch( Exception e) {
360 System.err.println("ERROR: can't get a component context from a running office ...");
361 e.printStackTrace();
362 System.exit(1);
367 /** Creates an empty spreadsheet document.
368 @return The XSpreadsheetDocument interface of the document. */
369 private com.sun.star.sheet.XSpreadsheetDocument initDocument()
370 throws RuntimeException, Exception
372 XComponentLoader aLoader = UnoRuntime.queryInterface(
373 XComponentLoader.class,
374 mxRemoteServiceManager.createInstanceWithContext(
375 "com.sun.star.frame.Desktop", mxRemoteContext));
377 XComponent xComponent = aLoader.loadComponentFromURL(
378 "private:factory/scalc", "_blank", 0,
379 new com.sun.star.beans.PropertyValue[0] );
381 return UnoRuntime.queryInterface(
382 com.sun.star.sheet.XSpreadsheetDocument.class, xComponent );
388 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */