November 11, 2010: 2000 2010 Teamdev LTD
November 11, 2010: 2000 2010 Teamdev LTD
November 11, 2010: 2000 2010 Teamdev LTD
Table of Contents
1. Introduction........................................................................................................................................1 2. System Requirements.......................................................................................................................2 3. JExcel Overview ................................................................................................................................3 4. Excel Automation Basics..................................................................................................................4 4.1. Creating a New Application ......................................................................................................4 4.2. Creating a New Workbook........................................................................................................4 4.3. Opening an Existing Workbook ................................................................................................4 4.4. Saving a Workbook...................................................................................................................5 4.5. Obtaining and Modifying Workbook Additional Information ......................................................5 4.6. Managing Worksheets ..............................................................................................................6 4.7. Working with Workbook Windows ............................................................................................7 4.8. Working with a List of Recently Opened Files ..........................................................................8 5. Event Listening and Handling ........................................................................................................10 5.1. Application Events ..................................................................................................................10 5.2. Workbook Events....................................................................................................................10 5.2.1. Listening to Workbook Events .....................................................................................11 5.2.2. Handling Workbook Events..........................................................................................11 5.3. Worksheet Events...................................................................................................................12 5.3.1. Listening to Worksheet Events ....................................................................................12 5.3.2. Handling Worksheet Events.........................................................................................12 6. Working with Cells...........................................................................................................................14 6.1. Referencing Cells ...................................................................................................................14 6.2. Setting New Values.................................................................................................................14 6.3. Obtaining Existing Values .......................................................................................................15 7. Working with Ranges ......................................................................................................................17 7.1. Referencing Ranges ...............................................................................................................17 7.2. Converting a Cell to a Range and Vice Versa ........................................................................17 7.3. Finding Values in Ranges .......................................................................................................18 7.4. Sorting a Range......................................................................................................................19 7.5. Obtaining Ranges Intersection ...............................................................................................19 7.6. Merging and Unmerging Cells of a Range .............................................................................20 8. Reading and writing bulk operations ............................................................................................21 8.1. Reading bulk operation...........................................................................................................21 8.2. Writing bulk operation .............................................................................................................21 9. Customizing Cells and Ranges ......................................................................................................22 9.1. Changing a Number Format ...................................................................................................22 9.2. Customizing Text Alignment and Orientation..........................................................................22 9.2.1. Changing Text Alignment .............................................................................................22 9.2.2. Changing Text Orientation ...........................................................................................23 9.3. Customizing Text Font ............................................................................................................23 9.4. Changing Background Pattern and Color in Cells ..................................................................25 9.5. Border Customization .............................................................................................................25 10. Integrating a Workbook into a Java Swing Application .............................................................27 10.1. Opening and Saving an Embedded Workbook.....................................................................27 10.2. Printing an Embedded Workbook .........................................................................................27 10.3. Displaying a Workbook in Static Mode .................................................................................27 10.4. Listening to JWorkbook Events ............................................................................................28 10.5. Multiple JWorkbook instances ..............................................................................................28 10.6. JWorkbook objects handling on application exit ...................................................................29
iii
11. Working with Native Peers and Thread Issues ...........................................................................31 12. Support...........................................................................................................................................32 12.1. JExcel Forum........................................................................................................................32 12.2. Reporting Problems..............................................................................................................32 12.3. Troubleshooting ....................................................................................................................32 13. Where to Get a New Version.........................................................................................................33
iv
Chapter 1. Introduction
There are lots of programming tasks that deal with generating reports in the tabular format. Usually such documents should be designed for reviewing by people who are not closely familiar with different technologies and prefer to obtain reports in a usual format. For Microsoft Windows users, the most common ofce solution is Microsoft Ofce, and when talking about electronic worksheets, it is undoubtedly Microsoft Excel. The JExcel library allows Java programmers for Windows to easily create, modify or display Microsoft Excel les. Using this library, you can work with workbook les, print a workbook, worksheet or even a specic range of cells, and modify cell values, cell number formats, etc. Also, there is an ability to customize cell appearance, including text font, cell background and border, text alignment and orientation, etc. JExcel can be used for solving different tasks from simple display of a workbook in a standalone Excel application to handling Excel events and embedding a workbook into Java Swing applications. The use of the library is very simple and doesnt require from a Java programmer specic knowledge of Microsoft Ofce programming. In the JExcel distribution you can view a demo application (JExcelDemo) showing how to embed an Excel workbook in a Java Swing application using the JWorkbook component. Each chapter below contains samples which you can also nd in the samples\Guide folder of the JExcel distribution.
Automation of an Excel application, workbooks, worksheets, etc. This is the core functionality of the JExcel library which allows you to work with Excel applications, workbooks, worksheets, ranges and cells.
Embedding a workbook in a Java Swing application. JExcel provides the JWorkbook component that allows embedding an Excel workbook in a Java Swing application as an ordinary Swing component.
worksheet respectively.
Handling workbook and worksheet events. Unlike event listeners, event handlers allow you not only to obtain events, but also affect the application behavior.
Working with native peers. Native peers are provided to allow you to add custom functionality based on JExcel.
When the Excel application is created, it is not visible. To make the application visible, the Application.setVisible() method should be called: if (!application.isVisible()) { application.setVisible(true); }
Similarly, the following call hides the application, but doesnt close it:
application.setVisible(false);
The sample above opens the Workbook.xls le protected with the password "password" in read-only mode.
The Workbook.save() method should be called only if the workbook was opened not in read-only mode, or was created and saved before. To save a newly created workbook or to save a workbook to another le or format, call the Workbook.saveAs() method:
//Saving the workbook to a new le in the default Excel format File newXlsFile = new File("C:\\Workbook2.xls"); workbook.saveAs(newXlsFile, FileFormat.WORKBOOKNORMAL, true); //Saving the workbook to a new le in the XML format File newXmlFile = new File("C:\\Workbook2.xml"); workbook.saveAs(newXmlFile, FileFormat.XMLSPREADSHEET, true);
The Workbook.saveAs() method saves a workbook to a different le and makes it active in Excel. To make the current workbook active after saving its copy, use the Workbook.saveCopyAs() method:
//Saving a copy of the workbook File workbookCopy = new File("C:\\WorkbookCopy.xls"); workbook.saveCopyAs(workbookCopy);
The Workbook.getHasPassword() method allows you to know whether a workbook is protected by a password:
if (workbook.getHasPassword()) { System.out.println("The workbook is protected with a password"); } else { System.out.println("The workbook is not protected with a password"); }
To know whether a workbook is opened in read-only mode, call the Workbook.isReadOnly() method: 5
All the workbook attributes mentioned above, except the workbook name, can be modied by calling the appropriate methods of the Workbook class:
workbook.setTitle("New title"); workbook.setPassword("xxx001"); workbook.setAuthor("John Smith");
The workbook name is the workbook le name which is modied automatically with the le name change. For the complete sample, please refer to the following le:
basics/WorkbookSample.java
To add a new worksheet to the workbook, use the Workbook.addWorksheet() method. This method allows you to add a new worksheet after the specied worksheet and assign the name of the new worksheet:
Worksheet sheet2 = workbook.getWorksheet("Sheet2"); workbook.addWorksheet(sheet2, "Custom sheet");
To add a new worksheet to the beginning of the worksheet list, pass null in place of the worksheet parameter or use the Workbook.addWorksheet() method with a single name parameter. The following function calls are equal:
{ Worksheet worksheet1 = workbook.addWorksheet("New sheet 1"); } { Worksheet worksheet1 = workbook.addWorksheet(null, "New sheet 1"); }
The Workbook.getWorksheets() method allows you to get a list of all workbook worksheets :
List worksheets = workbook.getWorksheets(); for (int i = 0; i < worksheets.size(); i++) { Worksheet worksheet = (Worksheet)worksheets.get(i); //Some action }
A worksheet also can be moved to a specied position using the Workbook.moveWorksheet() method. method. The method takes worksheet instance for moving and another after worksheet reference after 6
which, the moved worksheet will be placed. If null is passed to the after parameter, the worksheet will be moved to the beginning of the worksheet list:
//Moving customSheet to the end of the worksheet list workbook.moveWorksheet(customSheet, lastWorksheet); if (customSheet.getIndex() == workbook.getWorksheetsCount()) { System.out.println(customSheet.getName() + " is the last worksheet."); } //Moving customSheet to the beginning of the worksheet list workbook.moveWorksheet(customSheet, null); if (customSheet.getIndex() == 1) { System.out.println(customSheet.getName() + " is the rst worksheet."); }
In the same way you can copy worksheets using copyWorksheet() method as inside single workbook and between different workbooks:
GenericWorkbook workbook = application.createWorkbook(null); GenericWorkbook anotherWorkbook = application.createWorkbook(null); Worksheet worksheet = workbook.addWorksheet(null, null); //Here we copy worksheet as a last worksheet anotherWorkbook.copyWorksheet(worksheet, null, anotherWorkbook.getWorksheet(3)); //Here we insert worksheet copy before second worksheet anotherWorkbook.copyWorksheet(worksheet, anotherWorkbook.getWorksheet(2), null);
High level mergeWorkbook() method allows copying all worksheets from the specied workbook into another workbook instance:
GenericWorkbook rstWorkbook = application.createWorkbook(null); GenericWorkbook secondWorkbook = application.createWorkbook(null); //Merging workbook instances rstWorkbook.mergeWorkbook(secondWorkbook); //Merging workbook with workbook le rstWorkbook.mergeWorkbook(new File("c:/test.xls"));
Please note that this method copies only worksheets but skips VBA scripts. To remove a worksheet from a workbook, call the Workbook.removeWorksheet() method. Note that a workbook must contain at least one worksheet, so the last worksheet cannot be removed.
//Removing customSheet workbook.removeWorksheet(customSheet);
The Window class allows you to get and modify the window caption, size, zoom and window state. To work with window states, JExcel provides the Window.State class, which is an enumeration of MINIMIZED, MAXIMIZED and NORMAL constants. The following sample demonstrates how to get the window properties:
Window window = workbook.getWindow(); System.out.println("Caption: " + window.getCaption()); System.out.println("Width: " + window.getWidth()); System.out.println("Height: " + window.getHeight()); System.out.println("State: " + printState(window)); System.out.println("Zoom: " + window.getZoom()); System.out.println("Index: " + window.getIndex());
To know what workbook is currently displayed in the window, call the Window.getWorkbook() method:
Workbook workbook = window.getWorkbook();
If a workbook is opened or saved, it doesnt fall into the list of recently opened les automatically. The Application.addToRecentFiles() method allows you to add a le to the recently opened les list manually:
File le = new File("C:\\Workbook.xls"); application.addToRecentFiles(le);
JExcel provides the ApplicationEventListener interface for obtaining notications about application events. This interface resides in the com.jniwrapper.win32.jexcel package. The following sample demonstrates how to add a listener of application events:
Application application = new Application(); application.addApplicationEventListener(new ApplicationEventListener() { public void newWorkbook(ApplicationEventObject eventObject) { System.out.println(eventObject.getWorkbook().getName() + " workbook is created."); } public void openWorkbook(ApplicationEventObject eventObject) { System.out.println(eventObject.getWorkbook().getName() + " workbook is opened."); } });
A workbook is activated. A workbook is deactivated. A new worksheet is added to a workbook. Before a workbook is saved. Before a workbook is closed.
To obtain notications about workbook events, JExcel provides the WorkbookEventListener interface and WorkbookEventAdapter class which is added as a convenience for creating listener objects. To handle
10
controlled events, use the WorkbookEventHandler interface of the JExcel library. All these classes and interfaces reside in the com.jniwrapper.win32.jexcel package.
11
A worksheet is activated. A worksheet is deactivated. A cell range of values is changed. Selection in a worksheet is changed. Before processing a double-click event. Before processing a right-click event.
The JExcel library provides the WorksheetEventListener interface and the WorksheetEventAdapter class for listening to worksheet events and the WorksheetEventHandler for handling controlled events. All these classes and interfaces reside in the com.jniwrapper.win32.jexcel package.
12
13
The Cell class has the getRow() and getColumn() methods that let you know the cells coordinates. To know the cells address, call the Cell.getAddress() method:
String cellAddress = cell.getAddress();
The Cell.setName() method is used for creating named cells. To know whether the cell is named, call the Cell.getName() method. If the return value is null, the cell is not named, otherwise the method returns the cells name.
if (cell.getName() == null) { System.out.println(cell.getAddress() + " name is not set up."); cell.setName("Prot"); } else { System.out.println(cell.getAddress() + " name is \"" + cell.getName() + "\""); }
Referencing named cells is done in the same way as passing the cell name instead of its address:
//Obtaining a cell by its name Cell cell = worksheet.getCell("Prot");
14
The Cell.getNumber() method returns a numeric value as an instance of the java.lang.Number class. If the cell value cannot be converted to a number, null is returned. The Cell.getDate() method returns a date value as an instance of the java.util.Date class. If the cell value cannot be converted to the date format, null is returned. The Cell.getString() method returns a cell value in the string format.
//Getting a string value cell = worksheet.getCell("A3"); String strValue = cell.getString(); System.out.println("A3 string value: " + strValue); //Getting a double value cell = worksheet.getCell("C2"); Number numValue = cell.getNumber(); double doubleValue = numValue.doubleValue(); System.out.println("C2 double value: " + doubleValue); //Getting a Date value cell = worksheet.getCell("D1"); Date dateValue = cell.getDate(); System.out.println("D1 date value: " + dateValue);
If a cell contains a formula, methods for getting a cell value return a calculated result. To know whether the cell value is calculable or not, call the Cell.hasFormula() method, which returns true if the cell value is calculable or false if otherwise. The Cell.getFormula() method allows to obtain a cells formula in the string format:
//Getting cells formula and value cell = worksheet.getCell("B5"); if (cell.hasFormula()) { String formula = cell.getFormula(); System.out.println("B5 formula: " + formula); } long value = cell.getNumber().longValue(); System.out.println("B5 value: " + value);
15
Also, the Cell class provides functions letting you to know whether a cell is empty (the Cell.isEmpty() method), whether a cell contains a text value (the Cell.isText() method), or a numeric one (the Cell.isNumber() method) or an error value (the Cell.isError() method). All these methods return a boolean value. For the complete sample, please refer to the following le:
cell/GettingValuesSample.java
16
For creating compound ranges, the Range class provides the Range.include() method which takes a range to be included as an instance of the Range class or its string representation. The Range.include() method returns a Range class instance that represents the extended range. This makes it possible to create a compound range using a chain of method calls:
//Creating compound ranges { Range range = worksheet.getRange("B1:B4"); range.include("D11"); range.include("H1:H13"); } //More convenient way { Range range = worksheet.getRange("B1:B4").include("D11").include("H1:H13"); }
17
Case-sensitive search. To specify whether the search is case-sensitive or not, call the Range.SearchAttributes.setCaseSensitive() method passing true or false respectively. By default, the search is case-insensitive.
Forward or backward search direction. Call the Range.SearchAttributes.setForwardDirection() method passing true to set forward direction search or false if otherwise. By default, search is performed in forward direction.
Searching for the whole phrase. To set search for the whole phrase, call the Range.SearchAttributes.setFindWholePhrase() method passing true, otherwise Excel will try to nd the value as part of a phrase (the default setting).
Type of information to be searched for. Search can be performed in values, formulas or comments. To specify the type of information to be searched, call the Range.SearchAttributes.setLookIn() method which takes one of the predened instances of the Range.FindLookIn class: Range.FindLookIn.VALUES, Range.FindLookIn.COMMENTS or Range.FindLookIn.FORMULAS. The default value is Range.FindLookIn.VALUES.
If a value is found in the range, the Range.nd() method returns the cell where the value was found, otherwise the method returns null. The Range.ndNext() works similarly. The sample below demonstrates the technique of searching for values of different types:
//Getting a necessary range Range range = worksheet.getRange("A1:C5").include("D1"); //Specifying search attributes Range.SearchAttributes searchAttributes = new Range.SearchAttributes(); searchAttributes.setCaseSensetive(true); searchAttributes.setLookIn(Range.FindLookIn.VALUES); searchAttributes.setForwardDirection(true);
18
//Looking for a string value String strValue = "Grapefruit"; Cell cell = range.nd(strValue, searchAttributes); if (cell == null) { System.out.println("\"" + strValue + "\" was not found."); } else { System.out.println("\"" + strValue + "\" was found in " + cell.getAddress()); } cell = range.ndNext(); if (cell == null) { System.out.println("\"" + strValue + "\" was not found."); } else { System.out.println("\"" + strValue + "\" was found in " + cell.getAddress()); } //Looking for a long calculated value long longValue = 39; cell = range.nd(longValue, searchAttributes); if (cell == null) { System.out.println(longValue + " was not found."); } else { System.out.println(longValue + " was found in " + cell.getAddress()); }
19
20
The method wraps getValue2 interface of MS Excel and improves reading performance in several times.
The method wraps setValue2 interface of MS Excel and improves writing performance in several times. For the complete sample, please refer to the following le:
range/RangFillingSample.java
21
22
Working with vertical text alignment is similar to horizontal alignment: the Range.setVerticalAlignment() method sets a new value and the Range.getVerticalAlignment() returns the current setting as an instance of the TextAlignment class. The possible values are TextAlignment.BOTTOM, TextAlignment.CENTER, TextAlignment.DISTRIBUTED, TextAlignment.TOP and TextAlignment.JUSTIFY. If the range cells have mixed vertical alignment, the return value is null.
//Setting custom vertical text alignment range.setVerticalAlignment(TextAlignment.TOP); //Checking vertical text alignment if (range.getVerticalAlignment().equals(TextAlignment.TOP)) { System.out.println("A1:A3 range: new vertical text alignment was applied successfully."); } else { System.out.println("Vertical text alignment failed to be applied."); }
Font name
23
Call the Font.getName() method to get the font name, and the Font.setName(String) method to specify the font name.
Font size Call the Font.getSize() method to get the font size, and the Font.setSize() method to specify the font size.
General font styles The Font class allows you to specify whether the font is bold, italic or strike-through.
Font underline style The Font.UnderlineStyle class is an enumeration of ve underline styles supported by Excel: UnderlineStyle.NONE, UnderlineStyle.SINGLE, UnderlineStyle.SINGLEACCOUNTING, UnderlineStyle.DOUBLE, and UnderlineStyle.DOUBLEACCOUNTING. The Font.getUnderlineStyle() method returns the current underline style as an instance of the Font.UnderlineStyle class. The return value can be one of the predened values listed above. To change an underline style, call the Font.setUnderlineStyle() method.
Font color Call the Font.getColor() method to get the currently set font color, and the Font.setColor() method to specify the font color. A color value in both functions is an instance of the java.awt.Color class.
Font alignment style The Font class allows you to specify whether the text is normally aligned, subscript or superscript using the Font.setAlignment() method. This method takes one of the three predened instances of the Font.Alignment class: Alingment.NORMAL, Alignment.SUBSCRIPT or Alignment.SUPERSCRIPT. To obtain the current font alignment, call the Font.getAlignment() method.
To compare constant instances of the Font.Alignment or Font.UnderlineStyle classes, use the equals() method. For example:
public String getAlignmentAsString(Font.Alignment alignment) { if (alignment.equals(Font.Alignment.SUBSCRIPT)) {
24
Changing the background color. Call the Range.getInteriorColor() method to obtain the background color and the Range.setInteriorColor() method to specify the background color:
//Getting the interior color java.awt.Color interiorColor = range.getInteriorColor(); //Changing the interior color range.setInteriorColor(Color.BLUE);
Changing the background pattern. Excel allows you to set up various kinds of background patterns. JExcel provides the InteriorPattern class which is an enumeration of all kinds of background patterns supported by Excel version 1.5. The following sample demonstrates how to get and set the background pattern:
//Getting the interior pattern InteriorPattern interiorPattern = range.getInteriorPattern(); //Changing the interior pattern range.setInteriorPattern(InteriorPattern.DOWN);
Changing the background pattern color. Call the Range.getInteriorPatternColor() method to obtain the background pattern color and the Range. setInteriorPatternColor() method to specify the background pattern color:
//Getting the interior pattern color java.awt.Color interiorPatternColor = range.getInteriorPatternColor(); //Changing the interior pattern color setting range.setInteriorPatternColor(Color.RED);
25
26
Print dialog appears, the printing process starts after the user clicks the "Print" button. To display the Print dialog, call the JWorkbook.showPrintDialog() method:
JWorkbook jWorkbook = new JWorkbook(); jWorkbook.showPrintDialog();
To print a workbook without displaying the Print dialog, call the JWorkbook.print() method:
jWorkbook.print(1);
Also, the JWorkbook class lets you display an embedded workbook in preview mode. For this purpose, call the JWorkbook.printPreview() method.
A new workbook is created. A workbook is opened. A workbook is saved. A workbook is closing. A workbook is switched to print preview mode or back.
To listen to JWorkbook events, use the JWorkbookEventListener interface or the JWorkbookEventAdapter class. JWorkbookEventAdapter is an empty implementation of the JWorkbookEventListener interface. The following sample demonstrates the technique of how to add a listener of the JWorkbook events:
_workbook.addJWorkbookEventListener(new JWorkbookEventAdapter() { public void newWorkbook(JWorkbookEventObject eventObject) { System.out.println("New workbook: " + eventObject.getWorkbook().getName() + "."); } public void workbookOpened(JWorkbookEventObject eventObject) { System.out.println("Opened workbook: " + eventObject.getWorkbook().getName() + "."); } public void beforeWorkbookClose(JWorkbookEventObject eventObject) throws JWorkbookInterruptException { System.out.println("Workbook \"" + eventObject.getWorkbook().getName() + "\" closed."); } public void printPreviewStateChanged(JWorkbookEventObject eventObject) { if (eventObject.getJWorkbook().isPrintPreview()) { printLog("Workbook \"" + eventObject.getWorkbook().getName() + "\" is in the print preview mode."); } else { printLog("The print preview mode is closed."); } } });
For more information please refer to the following: JExcelDemo.java and JExcelDemo application
28
This code demonstrates creating two JWorkbook objects on tabbed interface. For more information please refer to corresponding samples in JExcel package.
29
JWorkbook jworkbook = (JWorkbook) jworkbookList.remove(0); if (jworkbook != null && !jworkbook.isClosed()) { jworkbook.close(); } } } });
For the full sample code please refer to MultipleJWorkbookWindows.java le in JExcel package.
30
The OleMessageLoop class provides two methods for executing methods in this thread: doInvokeLater() and doInvokeAndWait(). The difference between them is that the former returns immediately, and the latter blocks further execution while the task dened by Runnable method parameter is being executed. Use the doInvokeLater() method in a Swing thread for time-consuming tasks to prevent this thread from blocking. NOTE: Native windows should be opened in the OleMessageLoop of JWorkbook to correctly repaint objects. For the complete sample, please refer to the following le:
NativePeerSample.java
31
Installation instructions Programmers Guide Frequently Asked Questions (FAQ) page at: http://www.teamdev.com/jexcel/faq.jsf
If none of the above resources contain the required information, please e-mail us at:
[email protected]
12.3. Troubleshooting
To nd a solution to your problem, please visit the Troubleshooting page at:
http://www.teamdev.com/jexcel/tshoot.jsf
This page is regularly updated using information from support requests. If you dont nd a solution, please e-mail us at [email protected] or report the problem as described in the previous section.
32
33