Vous êtes sur la page 1sur 508

Programming e.

Spreadsheet Reports

Information in this document is subject to change without notice. Examples provided are fictitious. No part of this document may be reproduced or transmitted in any form, or by any means, electronic or mechanical, for any purpose, in whole or in part, without the express written permission of Actuate Corporation. 1995 - 2001 by Actuate Corporation. All rights reserved. Printed in the United States of America. Contains information proprietary to: Actuate Corporation 701 Gateway Boulevard South San Francisco, CA 94080 http://www.actuate.com The software described in this manual is provided by Actuate Corporation under an Actuate License agreement. The software may be used only in accordance with the terms of the agreement. Actuate Corporation trademarks and registered trademarks: Actuate, e.Analysis, e.Report, e.Reporting, e.Spreadsheet, Formula One, Internet Spreadsheet, Live Report Document, Live Report Extension, ReportBlast, ReportCast, Report Encyclopedia, SmartReports, Spreadsheets Everywhere, Tidestone, Transporter, Virtual Report Distribution, and XML Reports. Third party trademarks: ActiveX, Microsoft, Microsoft Access, Microsoft Excel, MS, MS-DOS, MSN, The Microsoft Network, Windows, Windows NT, Windows 95, Windows 98, Windows 2000 and/or other Microsoft products are either trademarks or registered trademarks of Microsoft. CT-Library is a trademark of Sybase, Inc. Databeacon is a trademark of Databeacon, Inc. Digital Creations and DCLC, are trademarks of Digital Creations, LC. Graphics Server is a trademark of Bits Per Second, Ltd. and Pinnacle Publishing, Inc. HDK is a registered trademark of Virtual Media Technology Pty Ltd. INFORMIX-ESQL/C is a trademark of Informix Software, Inc. InstallShield is a registered trademark of InstallShield Corporation. iPlanet, Netscape, Netscape Communications, Netscape Communicator, Netscape Enterprise Server, Netscape FastTrack Server, and Netscape Navigator are either trademarks or registered trademarks of Netscape Communications Corporation. Java and 100% Pure Java, ONC, Solaris, SPARC, Sun, and Sun Microsystems are either trademarks or registered trademarks of Sun Microsystems, Inc. JBuilder is a registered trademark of Inprise Corp. LEADTOOLS is a registered trademark of LEAD Technologies, Inc. Lotus and 1-2-3 are registered trademarks of Lotus Development Corporation. NobleNet and WinRPC are trademarks of NobleNet, Inc. Oracle Call Interface is a trademark of Oracle Corporation. Progress is a registered trademark of Progress Software Corporation. Sheridan Calendar Widgets is a trademark of Sheridan Software Systems, Inc. SmartHeap is a trademark of MicroQuill Software Publishing, Inc. Tools.h++ is a trademark of Rogue Wave Software, Inc. TrueType is a registered trademark of Apple Computer, Inc. UNIX is a registered trademark of X/Open Company, Ltd. Visual Cafe is a registered trademark of Symantec Corporation. XPrinter is a trademark of Bristol Technology, Inc. XPAT, created by James Clark, is licensed under the Mozilla license agreement. WinWidgets is a trademark of Simple Software, Inc. All other brand or product names are trademarks or registered trademarks of their respective companies or organizations. Document No. 010930-2-961003 September 12, 2001

Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
About Actuate e.Reporting Suite 5 . . . . . . . . About Programming e.Spreadsheet Reports . . . . Introduction . . . . . . . . . . . . . . . . . . . About Actuate e.Spreadsheet Designer product Online documentation. . . . . . . . . . . . . . . Using online manuals . . . . . . . . . . . . . About online help. . . . . . . . . . . . . . . . Using the online help. . . . . . . . . . . . . . Using online help search features . . . . . . . Typographical conventions . . . . . . . . . . . . Syntax conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi . . xxi . . xxi . . xxii . xxiv . xxiv . xxiv . xxiv . . xxv . xxvii .xxviii

Part 1

Programming with e.Spreadsheet


Chapter 1

Programming with e.Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . 1


About e.Spreadsheet Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using e.Spreadsheet Designer in applications and applets . . . . . . . . . . . . . . Launching e.Spreadsheet Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . Launching e.Spreadsheet Designer on Windows 95/98/NT/2000: . . . . . . . . Launching e.Spreadsheet Designer on Solaris: . . . . . . . . . . . . . . . . . . . . Launching e.Spreadsheet Designer on any platform from a command prompt: . Preventing the Designer from launching. . . . . . . . . . . . . . . . . . . . . . . . . Using the sample application and applet . . . . . . . . . . . . . . . . . . . . . . . . . . Running the sample code as an application . . . . . . . . . . . . . . . . . . . . . . . Running the sample code as an applet . . . . . . . . . . . . . . . . . . . . . . . . . . Instantiating e.Spreadsheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Loading a JBook dynamically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using e.Spreadsheet in an applications main method . . . . . . . . . . . . . . . . . Required files for e.Spreadsheet deployment . . . . . . . . . . . . . . . . . . . . . . . . Using the e.Spreadsheet API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . e.Spreadsheet packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . e.Spreadsheet primary classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . e.Spreadsheet utility classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 . 2 . 2 . 3 . 3 . 3 . 4 . 4 . 6 . 7 . 8 . 8 . 9 . 9 .10 .12 .14 .14

e.Spreadsheet Classes returned from JBook . . . . . . . . . . e.Spreadsheet Exception . . . . . . . . . . . . . . . . . . . . . e.Spreadsheet events and listeners . . . . . . . . . . . . . . . Using the e.Spreadsheet API constants . . . . . . . . . . . . . Using e.Spreadsheet as a JavaBean . . . . . . . . . . . . . . . . . Using add-in functions . . . . . . . . . . . . . . . . . . . . . . . Creating an add-in function with cell references and ranges. Setting recalculation for add-in functions . . . . . . . . . . . Getting the version number . . . . . . . . . . . . . . . . . . . . . Finding e.Spreadsheet demos and other help sources . . . . . . e.Spreadsheet-specific ReadMe files . . . . . . . . . . . . . . Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . API Help.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

. . . . . . . . . . . . . .

15 15 15 17 18 18 20 22 22 23 23 23 23 23

Chapter 2

Creating applications and applets . . . . . . . . . . . . . . . . . . . . . . . . . 27


Resolving Java security issues . . . . . . . . . . . . . . . . . . . Using digital signatures . . . . . . . . . . . . . . . . . . . . . Using RSA verification and the Java 2 Plug-in . . . . . . . . . Creating an RSA signed applet . . . . . . . . . . . . . . . . . Converting Netscape signed applets to RSA signed applets . Deploying applets . . . . . . . . . . . . . . . . . . . . . . . . . . Preparing an applet for Netscape Navigator . . . . . . . . . . Preparing an applet for Internet Explorer . . . . . . . . . . . Deploying signed applets . . . . . . . . . . . . . . . . . . . . Avoiding signing mistakes . . . . . . . . . . . . . . . . . . . . Reading, writing, and printing files from an applet . . . . . . . Reading, writing, and printing files with no Plug-in . . . . . Developing applications . . . . . . . . . . . . . . . . . . . . . . Creating a simple application . . . . . . . . . . . . . . . . . . Changing the class path on my machine . . . . . . . . . . . . Using the JVM -classpath option . . . . . . . . . . . . . . . . Adding a message box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 29 30 30 31 31 31 33 35 35 36 36 37 37 39 40 43

Chapter 3

Listening for events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45


Finding out whether a worksheet has been modified . . . Finding out whether the user is in edit mode . . . . . . . . Getting the most recent data entry . . . . . . . . . . . . . . Finding out which key the user pressed . . . . . . . . . . . Finding out when a user changes from one cell to the next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 46 47 47 48

ii

Finding out when a user changes worksheets . . . . . . . Maintaining cell format when the user enters a value . . . Canceling what the user enters in a cell . . . . . . . . . . . Converting pixels returned from a mouse event to twips .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

. . . .

.48 .48 .49 .50

Chapter 4

Increasing performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Using memory efficiently . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51 Getting and releasing locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53 Allocating row and column references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54 Increasing or decreasing garbage collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54 Understanding data structure and memory size . . . . . . . . . . . . . . . . . . . . . . . . . . .55 Basic Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55 Recalculating using setAutoRecalc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57 Maintaining speed when reading in large amounts of data . . . . . . . . . . . . . . . . . . . . .58 Finding out maximum length of a worksheet formula . . . . . . . . . . . . . . . . . . . . . . .59 Finding out the maximum number of characters in a cell . . . . . . . . . . . . . . . . . . . . . .59 Finding out why e.Spreadsheet uses memory even when it seems that nothing is happening .59

Part 2

Working with cells


Chapter 5

Manipulating cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Inserting cells using code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Working with rows and columns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . Selecting column or row headers . . . . . . . . . . . . . . . . . . . . . . . . . . . Getting row and column reference . . . . . . . . . . . . . . . . . . . . . . . . . . Determining the last row or column containing data. . . . . . . . . . . . . . . . Preventing the setMinCol method from returning an invalid argument error. . Working with ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Getting the row and column coordinates using a defined named range . . . . . Totaling values in columns where number of rows varies . . . . . . . . . . . . . Making named range values constant regardless of active cell pointer location Using the clearRange method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copying a range from one sheet to another . . . . . . . . . . . . . . . . . . . . . Clearing, cutting, and deleting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Clearing cell contents. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Clearing data only, leaving formatting . . . . . . . . . . . . . . . . . . . . . . . . Using the editCut method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64 .66 .66 .66 .67 .68 .69 .69 .69 .70 .70 .71 .71 .71 .72 .73

iii

Deleting unlocked cell contents after enabling protection . . . . . . . . . . . . . . . . . . . Shifting remaining rows and columns after delete . . . . . . . . . . . . . . . . . . . . . . . Copying and pasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copying and pasting data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pasting values only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating shortcut keys for copying and pasting . . . . . . . . . . . . . . . . . . . . . . . . . Selecting cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Making multiple, non-contiguous selections. . . . . . . . . . . . . . . . . . . . . . . . . . . Locating the active cell using code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Making the active cell visible . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Making the Enter key move the active cell to the next row by default . . . . . . . . . . . . Restricting user access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Restricting editing to certain columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Restricting users to delete values and formatting . . . . . . . . . . . . . . . . . . . . . . . . Setting cell protection for a range, column, or row . . . . . . . . . . . . . . . . . . . . . . . Maintaining protection on inserted ranges of cells when pasting in an unprotected range Allowing users to select only unprotected cells . . . . . . . . . . . . . . . . . . . . . . . . . Preventing users from entering data in locked cells without using cell protection . . . . . Limiting selection range to one cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Highlighting an entire row regardless of active cell location. . . . . . . . . . . . . . . . . . Disabling drag-and-drop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limiting characters users enter in a cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Limiting visible rows and columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Validating edit data from code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

73 73 74 75 76 76 77 77 77 78 78 80 80 80 81 81 82 82 83 83 84 84 85 85

Chapter 6

Manipulating cell data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87


Initiating in-cell editing using code . . . . . . . . . . Data entry using code . . . . . . . . . . . . . . . . . . Entering dates using code . . . . . . . . . . . . . . Writing a formula that increments the date . . . . Entering one value in all cells in a selected range . Loading data from an array . . . . . . . . . . . . . Importing large blocks of information . . . . . . . Sorting. . . . . . . . . . . . . . . . . . . . . . . . . . . Using the sort and sort3 methods . . . . . . . . . . Sorting dates or numbers with formatting . . . . . Sorting data with blank cells in the sort range . . . Concatenating text . . . . . . . . . . . . . . . . . . . . Accessing cell content . . . . . . . . . . . . . . . . . . Getting text value of a formula . . . . . . . . . . . Finding out cell data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 88 88 89 89 90 91 92 92 94 94 95 96 96 97

iv

Getting cell value prior to user editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98 Determining defined name status and location . . . . . . . . . . . . . . . . . . . . . . . . . .98 Returning string representations of cell location . . . . . . . . . . . . . . . . . . . . . . . . .98

Chapter 7

Referencing cells. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101


Working with defined names . . . . . . . . . . . . . . Creating or modifying a defined name. . . . . . . Creating worksheet-specific defined names . . . . Determining the number of defined names in use Referencing external cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 . 101 . 102 . 103 . 103

Part 3

Formatting
Chapter 8

Formatting worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107


Manipulating worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Adding a sheet to the end of the sheet list . . . . . . . . . . . . . . . . . . . . . . . . . Displaying a specific sheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deleting the active sheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing the look and feel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing the worksheet type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Hiding worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Getting the name of the active worksheet . . . . . . . . . . . . . . . . . . . . . . . . . Deselecting a worksheet using code . . . . . . . . . . . . . . . . . . . . . . . . . . . . Switching between worksheets with AllowSelections or ShowSelections set to false. Removing the view window border . . . . . . . . . . . . . . . . . . . . . . . . . . . . Exporting a worksheet with no gridlines to Excel . . . . . . . . . . . . . . . . . . . . Outlining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Working with Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Giving e.Spreadsheet focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Showing only part of the sheet when using multiple views . . . . . . . . . . . . . . . Changing view scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting default font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Resizing columns as data changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Grouping workbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Working with worksheet tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Moving or removing worksheet tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . Preventing tabs from reappearing at runtime . . . . . . . . . . . . . . . . . . . . . . . Moving through worksheets in a workbook. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 . 108 . 108 . 108 . 109 . 109 . 110 . 111 . 111 . 112 . 112 . 112 . 113 . 115 . 116 . 116 . 116 . 117 . 117 . 119 . 121 . 121 . 121 . 122

Naming worksheets. . . . . . . . . . . . . . . . . . . . . . Working with headers. . . . . . . . . . . . . . . . . . . . . . Getting and setting row and column header dimensions. Getting and setting header text . . . . . . . . . . . . . . . Setting header font . . . . . . . . . . . . . . . . . . . . . . Turning row and column headers off . . . . . . . . . . . . Resetting to default row and column header text . . . . . Entering multiple-line column and row headers . . . . . Working with columns and rows . . . . . . . . . . . . . . . . Hiding or showing a column or row . . . . . . . . . . . . Maintaining column widths when importing data . . . . Identifying and counting visible rows in a worksheet . . Freezing rows and columns . . . . . . . . . . . . . . . . . Changing default column width . . . . . . . . . . . . . . Getting column width in twips . . . . . . . . . . . . . . . Setting the first row or column displayed . . . . . . . . . Scrolling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scrolling through a worksheet using code . . . . . . . . . Leaving the scroll bar on . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . .

. 122 . 123 . 123 . 123 . 124 . 125 . 126 . 126 . 127 . 127 . 127 . 128 . 128 . 129 . 130 . 131 . 131 . 131 . 132

Chapter 9

Formatting cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133


Formatting a cell or range . . . . . . . . . . . . . . . . Formatting cells. . . . . . . . . . . . . . . . . . . . . . Setting cell background color . . . . . . . . . . . . Setting patterns for cells . . . . . . . . . . . . . . . Merging cells. . . . . . . . . . . . . . . . . . . . . . Displaying multiple-line data in one cell . . . . . . Turning cell protection on . . . . . . . . . . . . . . Turning type markers on . . . . . . . . . . . . . . . Formatting cell contents . . . . . . . . . . . . . . . . . Using vertical and horizontal alignment constants Applying different formatting to parts of a cell . . Showing formula text or returned value . . . . . . Hiding cell value . . . . . . . . . . . . . . . . . . . Hyperlinking from worksheet cells . . . . . . . . . . Using conditional formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 . 134 . 134 . 135 . 137 . 138 . 139 . 139 . 140 . 140 . 142 . 142 . 143 . 143 . 146

Chapter 10

Formatting data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151


Formatting numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Creating custom number formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

vi

Adding custom formats to the Format Cells dialog. . . . . . . . . . . Setting number format to currency . . . . . . . . . . . . . . . . . . . . Displaying numbers in other than scientific notation . . . . . . . . . Formatting dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Showing all four year-digits . . . . . . . . . . . . . . . . . . . . . . . . Displaying dates in local format . . . . . . . . . . . . . . . . . . . . . Displaying Julian dates in standard formats. . . . . . . . . . . . . . . Formatting text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Changing fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Formatting fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Making the default font scale proportionally . . . . . . . . . . . . . . Setting text color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting text direction . . . . . . . . . . . . . . . . . . . . . . . . . . . . Returning formatted text. . . . . . . . . . . . . . . . . . . . . . . . . . Setting a validation rule for a range . . . . . . . . . . . . . . . . . . . . . Displaying the contents of one cell in another . . . . . . . . . . . . . . . Using the TEXT worksheet function correctly . . . . . . . . . . . . . . . Manipulating worksheet errors . . . . . . . . . . . . . . . . . . . . . . . Hiding results of formulas that return 0 . . . . . . . . . . . . . . . . . . . Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Returning different results using getRowHeight and rangeToTwips . Returning 1 pixel or 15 twips too many with rangeToTwips. . . . . . Displaying more than 15 significant digits. . . . . . . . . . . . . . . . Using setColWidthAuto in classes other than JBook . . . . . . . . . . Exporting worksheets with more than 5,971 formatted cells to Excel.

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. 156 . 156 . 157 . 158 . 158 . 158 . 159 . 160 . 160 . 161 . 162 . 162 . 163 . 164 . 165 . 166 . 167 . 167 . 167 . 169 . 169 . 169 . 169 . 170 . 170

Chapter 11

Working with graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171


Adding graphics objects. . . . . . . . . . . . . . . . . Inserting an image into a worksheet . . . . . . . . Using addObject to add graphics objects. . . . . . Creating a graphics object in the cell a user selects Using setMode to draw graphics objects . . . . . . Adding and formatting charts. . . . . . . . . . . . Adding a listbox . . . . . . . . . . . . . . . . . . . Adding radio buttons . . . . . . . . . . . . . . . . Adding a text area . . . . . . . . . . . . . . . . . . Creating a custom polygon object. . . . . . . . . . Manipulating graphics objects . . . . . . . . . . . . . Setting backgrounds for graphics objects . . . . . e.Spreadsheet Patterns and Gradients . . . . . . . Getting the location of a graphics object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 . 172 . 173 . 174 . 175 . 176 . 176 . 178 . 179 . 180 . 181 . 181 . 182 . 183

vii

Getting the x, y coordinates of a cell in pixels . . . . . . . . . . . . . . . Making graphics objects transparent . . . . . . . . . . . . . . . . . . . . Setting size and position using setPos . . . . . . . . . . . . . . . . . . . Selecting graphics objects . . . . . . . . . . . . . . . . . . . . . . . . . . Preventing users from moving graphics objects . . . . . . . . . . . . . . Matching cell and graphics object index values . . . . . . . . . . . . . . Setting graphics object colors . . . . . . . . . . . . . . . . . . . . . . . . Deleting a graphics object during runtime . . . . . . . . . . . . . . . . . Positioning a check box in a column . . . . . . . . . . . . . . . . . . . . Creating a button that loads a VTS file from a local hard drive . . . . . Giving a graphics object focus with one click . . . . . . . . . . . . . . . Showing graphics objects when hiding adjacent cells. . . . . . . . . . . Forcing objectClicked and objectDblClicked to fire for graphics objects Adding and returning values . . . . . . . . . . . . . . . . . . . . . . . . . . Detecting value changes on graphics object clicks. . . . . . . . . . . . . Setting values or selections for check boxes or drop-down list boxes . . Getting a graphics object name from the ID number . . . . . . . . . . . Getting a graphics object ID from the object name . . . . . . . . . . . . Getting information from object events parameters. . . . . . . . . . . . Working with drop-down list boxes . . . . . . . . . . . . . . . . . . . . . . Inserting and populating a drop-down list box . . . . . . . . . . . . . . Changing an item in a drop-down list box . . . . . . . . . . . . . . . . . Displaying an item from a list box in a cell. . . . . . . . . . . . . . . . . Getting an item out of a drop-down list box . . . . . . . . . . . . . . . . Deleting items from a drop-down list box . . . . . . . . . . . . . . . . . Using draw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using draw to print with no borders or gridlines . . . . . . . . . . . . . Using draw to print data in columns to the same page . . . . . . . . . . Using draw to write a workbook to an image file . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. 184 . 184 . 184 . 185 . 185 . 186 . 187 . 187 . 188 . 188 . 189 . 190 . 190 . 191 . 191 . 191 . 192 . 192 . 192 . 193 . 193 . 193 . 194 . 195 . 195 . 197 . 201 . 201 . 201

Part 4

Publishing e.Spreadsheet
Chapter 12

Connecting to external data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205


Introduction and Update Information . . . . . . . . . . . . Report process API architecture . . . . . . . . . . . . . . Upgrading legacy code . . . . . . . . . . . . . . . . . . . Calling getLock and releaseLock in DataRangeIterator. Setting connection information with a properties file . . Using e.Spreadsheet parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 . 207 . 208 . 212 . 212 . 225

viii

Writing Callback classes for use on an Actuate server Using Callback classes on the reporting server . . . . Setting HTTP basic authentication in a data source. . Setting up a data source . . . . . . . . . . . . . . . . . . . Creating a connection to a database data source . . . Querying a database . . . . . . . . . . . . . . . . . . . Creating a data source connection to a file . . . . . . . Using {paramname}.txt in the file path . . . . . . . . . Working with character-delimited data source files . Working with positional text data source files. . . . . Adding column names when importing text data . . Setting data source refresh options . . . . . . . . . . . Refreshing source data . . . . . . . . . . . . . . . . . . Setting up a range . . . . . . . . . . . . . . . . . . . . . . Creating a data range. . . . . . . . . . . . . . . . . . . Setting data range properties . . . . . . . . . . . . . . Moving or deleting data ranges . . . . . . . . . . . . . Using XML and XSLT . . . . . . . . . . . . . . . . . . . . Importing XML using XSLT . . . . . . . . . . . . . . . Creating XSL stylesheets to convert XML . . . . . . . Using e.Spreadsheet JDBC data grouping in XSL . . . Using the level attribute in XSL . . . . . . . . . . . . . How to use the level attribute . . . . . . . . . . . . Using < and > symbols in an XSL stylesheet . . . . . Using a different XML parser or transformer . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . .

. 226 . 228 . 228 . 229 . 229 . 236 . 237 . 239 . 239 . 241 . 243 . 243 . 245 . 246 . 246 . 248 . 253 . 255 . 255 . 257 . 262 . 263 . 263 . 263 . 263

Chapter 13

Deploying on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267


Creating a simple applet . . . . . . . . . . . . . . . . . . . . . . . Embedding applets in a web page using one line of code. . . . . Finding out which browsers are compatible with e.Spreadsheet . Using VTS files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using write to save worksheets as HTML. . . . . . . . . . . . . . Using writeURL to save to a URL or output stream . . . . . . . . Using the writeURL servlet . . . . . . . . . . . . . . . . . . . . . . Loading worksheets with embedded applets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 . 270 . 271 . 271 . 272 . 274 . 282 . 284

Chapter 14

Deploying on a server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287


Creating a servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 Creating servlets and applications with no GUI overhead . . . . . . . . . . . . . . . . . . . . 292 Using the BookModel object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294

ix

Using e.Spreadsheet within Java Server Pages (JSP) . . . . . . . . . . . . . . . . . . . . . . . . 294 Analyzing user input from and returning HTML formatted data to the browser. . . . . . . . 297 Accessing the API using JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302

Part 5

Working with e.Spreadsheet input and output


Chapter 15

Reading and writing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307


Reading and writing e.Spreadsheet files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 Using ReadParams and WriteParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Setting file type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Setting code page type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 Setting password protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 Setting external data connection information using a properties file . . . . . . . . . . . 315 Loading a worksheet with an embedded applet. . . . . . . . . . . . . . . . . . . . . . . . . 315 Preventing setAllowInCellEditing from setting itself to true after saving and reloading a workbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Adding multiple VTS files to one workbook . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 Writing to a Blob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 Outputting a file to memory in a byte array . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 Reading from and writing to a BLOB from an Enterprise JavaBean. . . . . . . . . . . . . . 318 Determining BLOB length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319 Writing to an output stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 Working with delimited text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Converting data into tab-delimited text form . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Writing a tab-delimited file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 Writing a file as comma-delimited text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Preventing numbers from being interpreted as text when entering a tab-delimited text string 323 Writing a file in Excel 2000 format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Converting an e.Spreadsheet range to XML . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Writing a chart object as an image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330

Chapter 16

Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Changing print settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 Showing or hiding the print dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 Setting print orientation to landscape. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340

Printing in landscape orientation using draw . . . . . . . . Getting print area information . . . . . . . . . . . . . . . . Setting the print scale to fit-to-page. . . . . . . . . . . . . . Setting print area correctly. . . . . . . . . . . . . . . . . . . Clearing the print area after using setPrintArea. . . . . . . Setting printing to black and white . . . . . . . . . . . . . . Setting fit-to-page or fit-to-print using code . . . . . . . . . Using fit-to-page or fit-to-print with multiple print ranges Scaling to fit-to-page horizontally only. . . . . . . . . . . . Changing the page setup attributes using code . . . . . . . Printing headers, footers, and titles . . . . . . . . . . . . . . . Printing column and row headings . . . . . . . . . . . . . . Formatting print headers and footers . . . . . . . . . . . . Creating multiple-line print headers. . . . . . . . . . . . . . . Setting print titles . . . . . . . . . . . . . . . . . . . . . . . . . Printing row or column titles on every page . . . . . . . . . . Printing headers and footers using draw . . . . . . . . . . . . Odds and Ends of Printing. . . . . . . . . . . . . . . . . . . . Printing to a specific scale or number of pages . . . . . . . . . Printing a four-digit year in headers and footers . . . . . . . . Printing multiple jobs without running low on memory . . . Preventing print jobs from producing large spool files . . . . Preventing print output from getting cut off . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . .

. 341 . 341 . 341 . 342 . 342 . 343 . 343 . 344 . 345 . 345 . 346 . 346 . 347 . 349 . 349 . 350 . 350 . 351 . 352 . 353 . 353 . 354 . 354

Chapter 17

Converting e.Spreadsheet data to HTML . . . . . . . . . . . . . . . . . . 355


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installing the JSP Charting API. . . . . . . . . . . . . . . . . . . . . System requirements . . . . . . . . . . . . . . . . . . . . . . . . . About the JSP Charting API test web app . . . . . . . . . . . . . Web servers that support the JSP Charting API . . . . . . . . . . Installing the JSP Charting API under JRun . . . . . . . . . . . . . Installing the JSP Charting API into a JRun web application . . Sharing the JSP Charting API among JRun web applications . . Installing the JSP Charting API under TomCat . . . . . . . . . . . . Installing the JSP Charting API into a TomCat web application. Sharing the JSP Charting API among TomCat web applications Using tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Structure of a JSP Charting API tag . . . . . . . . . . . . . . . . . Tags with bodies and tags without bodies . . . . . . . . . . . . . About attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . About variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 . 356 . 357 . 357 . 358 . 359 . 361 . 363 . 366 . 368 . 369 . 372 . 372 . 374 . 374 . 375

xi

About the taglib directive . . . . . . . . . . . . . . . . . . . JSP Charting API examples by tag . . . . . . . . . . . . . . Tag reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . CreateDataQuery . . . . . . . . . . . . . . . . . . . . . . . . CreateDataRange . . . . . . . . . . . . . . . . . . . . . . . . CreateFileDataSource . . . . . . . . . . . . . . . . . . . . . . . CreateJDBCDataSource . . . . . . . . . . . . . . . . . . . . . ForEachDatapoint . . . . . . . . . . . . . . . . . . . . . . . . ForEachLegend . . . . . . . . . . . . . . . . . . . . . . . . . ForEachSeries . . . . . . . . . . . . . . . . . . . . . . . . . . GetBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GetCell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GetChart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GetRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . InsertCell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . InsertChart . . . . . . . . . . . . . . . . . . . . . . . . . . . . InsertChartImageMap . . . . . . . . . . . . . . . . . . . . . InsertDebug . . . . . . . . . . . . . . . . . . . . . . . . . . . InsertRange . . . . . . . . . . . . . . . . . . . . . . . . . . . InsertVersion . . . . . . . . . . . . . . . . . . . . . . . . . . . LoadBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . RefreshData . . . . . . . . . . . . . . . . . . . . . . . . . . . SetCell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SetDataQueryParameter . . . . . . . . . . . . . . . . . . . . SetRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UnloadBook . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the properties file . . . . . . . . . . . . . . . . . . . . . . Structure of the properties file . . . . . . . . . . . . . . . . . Changing default attribute values. . . . . . . . . . . . . . . Overriding attribute values . . . . . . . . . . . . . . . . . . Redefining attribute values . . . . . . . . . . . . . . . . . . Redefining attribute values for file isolation . . . . . . . Redefining attribute values for location isolation . . . . List of property keys and their tags . . . . . . . . . . . . . . e.Spreadsheet properties file for Data Pipes . . . . . . . . . Context parameters . . . . . . . . . . . . . . . . . . . . . . . . List of context parameters and their values . . . . . . . . . XML schemas for ranges and chart maps . . . . . . . . . . . . XML schema for ranges . . . . . . . . . . . . . . . . . . . . XML schema for chart image maps . . . . . . . . . . . . . . Viewing the JSP Charting APIs built-In XSLT documents .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. 377 . 379 . 382 . 382 . 383 . 386 . 387 . 388 . 389 . 389 . 390 . 390 . 391 . 397 . 398 . 399 . 401 . 402 . 403 . 405 . 405 . 406 . 407 . 407 . 408 . 408 . 409 . 410 . 411 . 412 . 413 . 413 . 414 . 414 . 416 . 417 . 418 . 419 . 420 . 420 . 422

xii

Chapter 18

Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
Troubleshooting worksheet functions that return #DIV/0! . . . . . . . . . . . . . Troubleshooting very slow screen redraws . . . . . . . . . . . . . . . . . . . . . . Determining the behavior of circular recalculations. . . . . . . . . . . . . . . . . Comparing IF condition statement values correctly when a text value is entered Using e.Spreadsheet in the main class causes problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424 . 424 . 424 . 425 . 426

Chapter 19

Using e.Spreadsheet with Unix . . . . . . . . . . . . . . . . . . . . . . . . . . 427


Introduction . . . . . . . . . . . . . . . . . . . . . . . Using e.Spreadsheet on Unix with a graphics device Using e.Spreadsheet on Unix without X-Windows . Using setColWidthAuto with no GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428 . 428 . 429 . 431

Appendix A

Additional Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433


e.Spreadsheet maximums and minimums . . Links to more information . . . . . . . . . . . Converting legacy code from AWT to Swing . e.Spreadsheet files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 . 435 . 435 . 436

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443

xiii

xiv

Intro ductio n

Introduction

xv

About Actuate e.Reporting Suite 5


Actuate is the leading provider of information delivery solutions for e.Business. e.Business customers use Actuate e.Reporting Suite 5 to develop and deploy high resolution structured content to hundreds of thousands of users. Actuate takes web reporting to the next level by providing options for needs as varied as seamless personalized web pages and traditional online and printed reports. Actuates customer list includes commercial banks, securities, financial services, insurance, high tech, telecom, .com, internet, global 2000, and federal government. OEMs, system integrators, and others building e.Business sites for information delivery face challenges. Actuate e.Reporting Suite 5 offers the following solutions. Challenge Delivering high resolution information Viewing structured content Actuate solution DHTML provides a fast, nodownload option Supporting standard browsers means there is no need to support installations of plug-ins for hundreds of thousands of users Provides template-based design and display Ability to support a million hits per day per CPU Open security directory integration and page security Open server provides access to content from other applications PDF provides high-resolution printed copy XML output provides access to data across applications

Compromising information display because of lack of integrated tools Exploding use of web-based content delivery Delivering personalized secure information Reusing existing integrated content Maintaining data integrity on hard copy Transferring information into other applications

Actuate tools and reports do the following:


s s s

Solve complex data access problems. Solve formatting problems that go beyond the scope of other tools. Scale to support hundreds of thousands of users.

xvi

Programming e.Spreadsheet Reports

The following summary describes the products in Actuate e.Reporting Suite 5. Product name Actuate e.Report Designer Professional Use An object-oriented application used by professional developers of structured content to design, build, and distribute report object designs for delivery on the Web. The Actuate Basic Language and Actuate Foundation Class Library support extensive customization capabilities. Actuate ActiveX Controls embed Actuate reporting functionality into custom applications. Actuate Requester API accesses attributes and values of report parameters, changes the values of report parameters, controls how and when a report is generated, displays and prints reports, and configures report print setup. Access the Requester API using Actuate Basic, Visual Basic, C, or C++. Actuate search extension API supports developing search extensions to transfer data to any third-party productivity or analysis tool. Actuate report server API implements common Report Encyclopedia tasks, integrates report server features into existing corporate applications, automates routine or time-consuming tasks, and implements new feature groupings for custom business processes. Access the report server API using C++. Actuate Report Server Security Extension supports the use of third-party security tools. Actuate archive driver supports the use of third-party archiving software and hardware.

Actuate SDK (Software Development Kit) included as part of Actuate e.Report Designer Professional

Introduction

xvii

Product name Actuate e.Report Designer

Use An application that complements e.Report Designer Professional and is used by business users to design and distribute a variety of reports. These reports require no programming. This application supports both modifying complex reports and using sophisticated components from libraries. A report development application used by Java developers to design and distribute a variety of reports. 100% Java compliant, the e.Report Designer Java Edition includes both AWT and Swing APIs. An application that supports designing, creating, and distributing custom spreadsheets over the web. Users can dynamically generate richly formatted Excel and spreadsheet-based reports from Actuate e.Reporting Server. These spreadsheets can be part of an application, an applet, or a Java Bean. A server application that generates Live Report Documents, manages them in the Report Encyclopedia, and makes them available to users. This application includes open server functionality that supports the use of third-party report generators with the Actuate e.Reporting Server. This product includes Actuate Administrator Desktop, an application for system and network administrators to manage and control one or more Actuate report servers. This product also includes Actuate ReportCast that transforms the Report Encyclopedia into a dynamic, secure web site. ReportCast provides the foundation for Channels and seamless integration with other web sites.

Actuate e.Report Designer Java Edition

Actuate e.Spreadsheet Designer

Actuate e.Reporting Server

xviii

Programming e.Spreadsheet Reports

Product name Actuate e.Reporting Server Progress Edition

Use A server application designed to work exclusively with Progress databases that generates Live Report Documents, manages them in the Report Encyclopedia, and makes them available to users. This application includes open server functionality that supports the use of thirdparty report generators with the Actuate e.Reporting Server. This product includes Actuate Administrator Desktop, an application for system and network administrators to manage and control one or more Actuate report servers. This product also includes Actuate ReportCast that transforms the Report Encyclopedia into a dynamic, secure web site. ReportCast provides the foundation for Channels and seamless integration with other web sites. An application that adds page security to the basic e.Reporting Server. Page security supports personalized viewing of parts of reports for various users. An application designed to work exclusively with Progress databases that adds page security to the basic e.Reporting Server. Page security supports personalized viewing of parts of reports for various users. An application used to transform data from an Actuate e.report into interactive information. Users can view and analyze data to determine relationships and trends. Actuate e.Analysis is an optional product that installs with ReportCast and the e.Reporting Server and extends its functionality.

Actuate Advanced e.Reporting Server

Actuate Advanced e.Reporting Server Progress Edition

Actuate e.Analysis

Introduction

xix

Product name

Use

Actuate e.Spreadsheet Option An open server application that generates Excel spreadsheets from e.Spreadsheet Designer files. With this product customers manage spreadsheet reports and analytics within the Actuate e.Reporting Server, and save Actuate reports as richly formatted Excel spreadsheets. Actuate End User Desktop An application used by end users to request, generate, view, and print report documents. The ReportQuery capabilities enable seamless transfer of data from an Actuate report to any productivity tool or analysis tool. Application for end users to find, view, and print report documents. The ReportQuery capabilities are also part of the Actuate Viewer. Application for end users that works with both Microsoft Internet Explorer and Netscape Navigator to support report viewing and printing on the Web.

Actuate Viewer

Actuate Live Report Extension (LRX)

Actuate Viewer and Actuate Live Report Extension (LRX) are included with all products except Actuate e.Report Designer Java Edition and Actuate e.Spreadsheet Designer.

xx

Programming e.Spreadsheet Reports

About Programming e.Spreadsheet Reports


Introduction
Each article in Programming e.Spreadsheet Reports provides a concise discussion and code example answering a common question about how to use the e.Spreadsheet API. Taken as a whole, Programming e.Spreadsheet Reports, containing over 300 topics, seeks to provide a comprehensive technical reference for software developers. Browsing through Programming e.Spreadsheet Reports will yield an overview of e.Spreadsheets capabilities. However, most developers will use this publication as a reference, seeking answers to questions as they arise during the software development process. Programming e.Spreadsheet Reports is divided into chapters based on general areas of the functionality of e.Spreadsheet. Topics within each chapter are grouped together based on a more or less common topical thread. Where a clear subtopic exists, topics are further divided within each chapter into subcategories under the general chapter headings. Some topics could correctly appear in more than one section. Where this occurs, a cross-reference to a related topic appears. Each article includes a brief synopsis and any related specific details. Most topics also include:

Code Examples:
A code snippet, sometimes a complete small program, that illustrates the topic. Some articles also include a brief overview of a significant e.Spreadsheet method, including:

Syntax:
The syntax section illustrates the proper syntax and available parameters of a method illustrated in the topic.

Parameters:
A table that lists and describes each parameter of the e.Spreadsheet method treated within the topic and any other options that work within the method.

Introduction

xxi

About Actuate e.Spreadsheet Designer product


Actuate e.Spreadsheet products documentation includes printed manuals, an installation guide, online help, user documentation in PDF format, and release notes. Information about the product that could not be included before the book printing deadline is in the release notes. The Actuate web site, http://www.actuate.com, contains late-breaking news about the product and its features, as well as product update information. To obtain the password necessary to access the portion of the web site available only to customers, telephone Actuate Customer Support. The engineers in Actuate Customer Support can also help you with technical questions about the product according to your service contract. The Customer Support telephone number, fax number, and e-mail information can be found among the printed materials in the product box. The examples folder in the product contains numerous demos, example XSLT files, and example e.Spreadsheet applets, applications, and add-in functions. The servlet folder contains an example servlet. Each folder contains a variety of files often including a text file that discusses how the example works. The printed and online documentation includes the following manuals. For information about Installation Late-breaking information about the software and documentation How to design e.Spreadsheet templates with the e.Spreadsheet Designer How to use the e.Spreadsheet Designer as a stand-alone spreadsheet How to establish a data source connection and format and manipulate data See the following Installation guide Release notes

Designing e.Spreadsheet Reports

XtraGraphics

xxii

Programming e.Spreadsheet Reports

For information about Alphabetical and categorical listings of the 326 worksheet functions in e.Spreadsheet Proper function usage and syntax How to use each function Cross-references to related functions Programming with e.Spreadsheet How to program e.Spreadsheet reports using the e.Spreadsheet API Overview of classes Code examples

See the following

e.Spreadsheet Function Reference

XtraGraphics

Programming e.Spreadsheet Reports

XtraGraphics Installing and using e.Spreadsheets custom JSP tags Inserting spreadsheet-driven charts with interactive drill-down functionality into web pages Advanced JSP topics such as using the properties file and understanding XML schemas

Programming e.Spreadsheet Web Applications

XtraGraphics

Introduction

xxiii

Online documentation
The information in the printed manuals is also available as online manuals in Adobe Acrobat PDF format and in the online help system for the Actuate products. For products without a Windows interface, such as the various versions of Actuate e.Reporting Server, Actuate e.Report Designer Java Edition, Actuate ReportCast, and Actuate e.Analysis, we provide HTML help files, which are installed automatically with the product and can be viewed with standard browsers. Actuate e.Spreadsheet Designer provides JavaHelp online help, which is installed automatically with the product and can be viewed through the e.Spreadsheet Designer user interface.

Using online manuals


The online manuals do not install automatically with the product. On the product CD, you find those files in the Manuals directory. Open the introductory PDF file to get an overview of the manuals. Copy to your local drive this file and the files for each book you want to be able to use online. The items in the table of contents and the page numbers in the index both contain links to the appropriate topics in the text. In the index, you access the link by positioning your cursor over the page number, not the topic.

About online help


Online help is available for both Designing e.Spreadsheet Reports and e.Spreadsheet Function Reference. Using online help, you can select a topic from the table of contents for either book or you can conduct a search for a keyword or phrase. To access online help from e.Spreadsheet Designer, choose HelpContents and Index or choose the Help button.

Using the online help


The online help interface consists of two windows for accessing and viewing help topics. The window on the left displays the table of contents in the form

xxiv

Programming e.Spreadsheet Reports

of a list of topics. The window on the right displays the text for a selected topic, as shown in the following illustration.
Back Forward Print topic Page setup for printing

Search e.Spreadsheet Function Reference topics Designing e.Spreadsheet Reports topics

The tabs at the top of the left window display three different help views. The two book tabs display help topics. The book to the left displays topics about Designing e.Spreadsheet Reports. The book in the middle displays topics about e.Spreadsheet Function Reference. To conduct a keyword search, choose the tab to the right. Above the windows, the toolbar buttons support paging back and forward, printing, and accessing print setup.

Using online help search features


How to search for a topic
1 Choose Search. 2 In Find, type the word or phrase for which you want to search.

Introduction

xxv

Use short phrases. The software searches for words with common roots, so if you search for build, e.Spreadsheet help might return built, builder, building, and builds. Do not use the period character (.) in the search phrase. 3 Press Enter. e.Spreadsheet Help displays a list of matching topics, ranked in order of best to worst match.
Search text List of topics Ranking circle Ranking number

The ranking circle indicates how well the topic matches your search criteria. A completely filled-in the circle indicates a higher ranking. Topics are ranked higher if they contain all the words from the search phrase and if those words appear close together in the text, in the same form, for example print rather than printing, in the same order, or with fewer intervening words. The ranking number indicates the number of times any of the words you searched for appear in this topic. 4 Select a topic. The topic text appears in the right-hand window.

xxvi

Programming e.Spreadsheet Reports

Typographical conventions
The following table describes the typographical conventions used in this guide. Item Code examples File names Convention Sans serif Initial letter capitalized. Except e. Report Designer Java Edition, where file names are case sensitive A + sign between the keys means to press both keys at the same time Capitalized. No bold. Separated from main menu item with small arrow Sans serif Italics Example
Dim As String

Detail.roi

Key combination

Ctrl+Shift

Menu items Submenu items

File FileNew

User input or user response User input in XML and Java code

M*16* chkjava.exe cab_name.cab

Introduction

xxvii

Syntax conventions
The following table describes the symbols used to present the syntax. Symbol [] Description Optional item Array subscript <> Argument you must supply Delimiter in XML {} Groups two or more mutually exclusive options or arguments, when used with a pipe Defines array contents Delimiter of code block Example [Alias<alias name>] blob[ ] <expression to format> <tr> {While | Until}

{0, 1, 2, 3} public ACJDesigner( ) { } Exit {Do | For | Function | Sub} int var |4

Separates mutually exclusive options or arguments in a group Java OR operator

xxviii

Programming e.Spreadsheet Reports

Part

1
Part 1

Programming with e.Spreadsheet

Part 1, Programming with e.Spreadsheet

29

30

Programming e.Spreadsheet Reports

Chapter

1
Chapter 1

Programming with e.Spreadsheet

This chapter contains the following topics:


s s s s s s s

About e.Spreadsheet Designer Using e.Spreadsheet as a JavaBean Finding e.Spreadsheet demos and other help sources Required files for e.Spreadsheet deployment Using the e.Spreadsheet API Using the sample application and applet Javadoc-generated guide to all of e.Spreadsheets public API. The API Help is available as Javadoc in the install_dir/help/awtdoc and install_dir/ help/swingdoc directories and as an HTML Help file in the install_dir/ help/win directory.

Chapter 1, Programming with e.Spreadsheet

About e.Spreadsheet Designer


The e.Spreadsheet Designer is e.Spreadsheets workbook data entry and formatting tool.

Using e.Spreadsheet Designer in applications and applets


You have the option of providing e.Spreadsheet Designer functionality automatically on any application or applet that displays a e.Spreadsheet workbook.

Accessing e.Spreadsheet Designer from an application or applet.


To launch the e.Spreadsheet Designer from a e.Spreadsheet application or applet: 1 Select a worksheet cell. 2 Press F3. The e.Spreadsheet Designer appears in a new window. Users automatically have access to the e.Spreadsheet Designer when you ship the e.Spreadsheet JAR file f1j9swing.jar. This JAR file must be on the applications classpath for the software to work.

Launching e.Spreadsheet Designer


You can launch the e.Spreadsheet Designer as a standalone application.

Programming e.Spreadsheet Reports

Launching e.Spreadsheet Designer on Windows 95/98/NT/ 2000:


1 Double-click on the F1J9.exe file. or 1 Choose StartProgramsActuate e.Reporting Suite 6Actuate e.Spreadsheet Designer.

Launching e.Spreadsheet Designer on Solaris:


A shell script, included with the installer, launches the e.Spreadsheet Designer. 1 At the command prompt, switch to the installation directory. 2 Execute the following command:
./f1j9

If you chose a JRE previous to 1.2.x when installing e.Spreadsheet, you will have to modify the shell script created by the installer to include swingall.jar on the classpath. For more information, see the release notes.

Launching e.Spreadsheet Designer on any platform from a command prompt:


1 Open a command prompt and switch to the directory that contains f1j9swing.jar. 2 Execute the following command:
java -cp f1j9swing.jar com.f1j.swing.designer.Designer

About Classpath settings


Launching the Designer from the Windows Start menu, an EXE file, or from a Solaris shell script sets the classpath automatically. Other modes of launching the Designer may require you to change classpath settings. The following command launches the basic Designer without Designer Help, XML and XSLT processing functionality, and international language support.
java -cp f1j9swing.jar com.f1j.swing.designer.Designer

To launch the Designer and provide access to its expanded functionality, such as online Designer Help, XML and XSLT processing functionality, and international language support, you need to add JAR files to the classpath. You do this by listing the relevant JAR files after the -cp (classpath) command option. For example, to launch the e.Spreadsheet Designer with Designer Help, execute the following command:
java -cp f1j9swing.jar;jh.jar;f1help.jar

Chapter 1, Programming with e.Spreadsheet

com.f1j.swing.designer.Designer

On Solaris and other UNIX platforms, replace the semicolons (;) in this command with colons (:). The following table lists the JAR files you an add to the classpath to add functionality to the e.Spreadsheet Designer. The e.Spreadsheet Designer installation copied all JAR files except the language files into the Actuate6 directory on your hard disk. The language JAR files appear in a separate subdirectory called Actuate6\local.. JAR file name jh.jar f1help.jar jaxp.jar xalan.jar xerces.jar language JAR files, for example: f1j9_ja.jar Functionality Adds the online Designer Help. Both JAR files must be on the classpath in order for the help to be available. Provides XML and XSLT processing. All three JAR files must be on the classpath in order for you to access this functionality. Provides access to different languages in the e.Spreadsheet Designer. For information on how to deploy e.Spreadsheet in different languages, see e.Reporting for Multiple Locales. Providing textures for filling drawing objects.

f1jtextures.jar

Preventing the Designer from launching


Calling the setAllowDesigner method with a parameter of false will prevent the e.Spreadsheet Designer from launching at runtime.

Code Example
jbook1.setAllowDesigner(false);

Using the sample application and applet


The sample e.Spreadsheet application and applet code examples below demonstrate the very basic code necessary to create and display a spreadsheet. You can use this code to test whether e.Spreadsheet is properly installed and running on your machine. Running the code displays a spreadsheet with the formula bar, row and column headings, scroll bars, and some formatted text in

Programming e.Spreadsheet Reports

one of the spreadsheet cells. You can find a file containing this code, Welcome.java, in install_directory/examples/swing/welcome. You can compile and execute the example program as an application or as an applet embedded in an HTML file. To view the HTML code necessary to embed the applet, see Running the sample code as an applet later in this chapter.Running the sample code as an applet. JBook requires a graphical user interface (GUI). This presents a problem on UNIX systems that have no X server or software to emulate a GUI. You cannot use these systems to create or use a JBook. If your application does not require a GUI, you should use the BookModelImpl class instead, which has almost all of the functionality of JBook but no GUI. For more information, see Using e.Spreadsheet on Unix without X-Windows in Chapter 19, Using e.Spreadsheet with Unix.Using e.Spreadsheet on Unix without X-Windows.
import java.awt.*; import java.awt.event.*; import com.f1j.swing.*; import javax.swing.*; public class Welcome extends JApplet { JBook jBook1 = new JBook(); public void Welcome() { } //Initialize the applet public void init() { this.setSize(new Dimension(400,300)); try { // Call the Formula One setText API to place text // into a cell jBook1.setText(2, 0, "Welcome to Formula One for " + "Java: The Internet Spreadsheet"); // Add a format to the cell com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jBook1.getCellFormat(); CellFormat1.setHorizontalAlignment( CellFormat1.eHorizontalAlignmentCenterAcrossCells); CellFormat1.setFontBold(true); CellFormat1.setFontItalic(true); CellFormat1.setFontSize(210); jBook1.setCellFormat(CellFormat1, 2, 0, 2, 6); } catch (com.f1j.util.F1Exception e) { // catch any exceptions in case something fails setting

Chapter 1, Programming with e.Spreadsheet

// the text System.out.println(e.getMessage()); } this.getContentPane().add(jBook1, BorderLayout.CENTER); } public static void main(String args[]){ // Create a Frame to place our application in. Frame myFrame = new Frame ("Getting Started"); myFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { System.exit(0); } }); // Create an instance of the Welcome class Welcome myApp = new Welcome(); myFrame.add ("Center", myApp); myApp.init(); // Resize the Frame to the desired size, and make it visible myFrame.setSize(600,400); myFrame.show(); // Run the methods the browser normally would myApp.start(); } }

Running the sample code as an application


First compile it into a class file using your development environments compiler or the Java command-line compiler, javac. If Welcome.java is in the same directory as f1j9swing.jar, open the command prompt, change to that directory, then type in the following Java command:
javac -classpath f1j9swing.jar Welcome.java

Then you can execute the resulting class within your development environment or from a command prompt using the Java command java. If Welcome.class is in the same directory as f1j9swing.jar, open the command prompt, change to that directory, then type in the following Java command:
java -cp .;f1j9swing.jar Welcome

Programming e.Spreadsheet Reports

Running the sample code as an applet


First, compile it into a class file using the instructions above for compiling the application code. Then, create an HTML file in which to display the class as an applet. Because the popular browsers (Netscape Navigator and Internet Explorer) diverge in how they deal with applets that require recent versions of the JVM, you must create HTML that contains specialized tags for IE and different tags for Netscape. Sun Microsystems provides an HTML Converter utility that automatically converts your <APPLET> tags to the appropriate IE and Netscape-specific tags. You can download this utility at java.sun.com/ products/plugin/index.html. Following is sample HTML code to display the applet using the <APPLET> tag. This code assumes Welcome.class and f1j9swing.jar are in the same directory.
<HTML><HEAD> <TITLE>Live Spreadsheet Page</TITLE> </HEAD> <BODY> <APPLET CODE="Welcome.class" ARCHIVE="f1j9swing.jar" WIDTH=400 HEIGHT=300></APPLET> </BODY></HTML>

Following is that same HTML code after being run through Suns HTML Converter.
<HTML> <HEAD> <TITLE>Live Spreadsheet Page</TITLE> </HEAD> <BODY> <!--"CONVERTED_APPLET"--> <!-- CONVERTER VERSION 1.0 --> <OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH = 400 HEIGHT = 300 codebase="http://java.sun.com/products/plugin/1.2/jinstall-12win32.cab#Version=1,2,0,0"> <PARAM NAME = CODE VALUE = "Welcome.class" > <PARAM NAME = ARCHIVE VALUE = "f1j9swing.jar" > <PARAM NAME="type" VALUE="application/x-java-applet;version=1.2"> <COMMENT> <EMBED type="application/x-java-applet;version=1.2" java_CODE = "Welcome.class" java_ARCHIVE = "f1j9swing.jar" WIDTH = 400 HEIGHT = 300 pluginspage="http://java.sun.com/products/plugin/1.2/plugininstall.html"><NOEMBED></COMMENT>

Chapter 1, Programming with e.Spreadsheet

</NOEMBED></EMBED> </OBJECT> <!-<APPLET CODE = "Welcome.class" ARCHIVE = "f1j9swing.jar" WIDTH = 400 HEIGHT = 300 > </APPLET> --> <!--"END_CONVERTED_APPLET"--> </BODY> </HTML>

The <APPLET> tag has been replaced with code containing the <OBJECT> tag (used by Internet Explorer) and the <EMBED> tag (used by Netscape Navigator). Netscape ignores IEs <OBJECT> tag, while IE ignores anything within <COMMENT> tags. Opening this converted HTML file in a browser will display the spreadsheet. This HTML code contains the parameter pluginspage. This refers to the Java Plug-in, another Sun Microsystems utility that you must use if you want to run Swing applets in current browsers. The plug-in is necessary because Internet Explorer and Netscape Navigator do not contain the latest version of the JVM. When users whose computers dont already have the latest JVM encounter a web page containing an applet that uses Swing Java software, they must download and install the Java Plug-in software before they can run that applet. The plug-in automatically substitutes a more recent version of the Java Virtual Machine for the browsers older versions. For information about downloading and using the Java Plug-in, see Sun Microsystems web site at java.sun.com.

Instantiating e.Spreadsheet
You can instantiate e.Spreadsheet as a standalone application or within a separate application as illustrated in the code examples below.

Loading a JBook dynamically


To dynamically create an instance of a JBook, define and load it as a new class as shown in the code example.

Code Example
The following code dynamically creates an instance of JBook, adds it to a JFrame, and calls the setShowEditBar method.

Programming e.Spreadsheet Reports

try { Class myClass = Class.forName("com.f1j.swing.JBook"); Object myObj = myClass.newInstance(); java.awt.Component jbook1 = (java.awt.Component) myObj; jbook1.setBounds(12, 3, 407, 218); this.getContentPane().add(jbook1); this.repaint(); Class parmTypes[] = new Class[1]; parmTypes[0] = Boolean.TYPE; java.lang.reflect.Method myShowBar = myClass.getMethod( "setShowEditBar", parmTypes); Object parmValues[] = new Object[1]; parmValues[0] = new Boolean(true); myShowBar.invoke(myObj,parmValues); } catch (Exception eJ){ }

Using e.Spreadsheet in an applications main method


To use e.Spreadsheet in the main method of an application, declare the e.Spreadsheet object as static. Because main is a static member of the class, it can access static declared member variables.

Code Example
static com.f1j.swing.JBook jbook1 = new com.f1j.swing.JBook();

Required files for e.Spreadsheet deployment


To deploy a project using the e.Spreadsheet graphical user interface, developers need to include f1j9swing.jar. To deploy e.Spreadsheet on a database or application server, specialized JAR files can be created from f1j9swing.jar. For more information, see Reducing applet and JavaBean size for use over the Internet in Chapter 13, Deploying on the Web.Reducing applet and JavaBean size for use over the Internet.

Chapter 1, Programming with e.Spreadsheet

To deploy e.Spreadsheet in an application or applet, use the following files. For a complete listing of e.Spreadsheet files, see e.Spreadsheet files in Chapter 19, Additional Information..e.Spreadsheet files. File name f1j9swing.jar xalan.jar, xerces.jar, and jaxp.jar f1help.jar and jh.jar language JAR files Description This file contains all of e.Spreadsheets functionality, including access to the e.Spreadsheet Designer. (optional) These JARs must be included in projects that use the XMLWriter or ChartImageEncoder classes or that use external data consisting of XML files or JDBC databases formatted with XSLT. (optional) Include these JAR files in projects in which you want the e.Spreadsheet Designer to include the Designer Help online help system. (optional) Include appropriate language JAR files in projects in which you want the e.Spreadsheet Designer user interface to be translatable into other languages. For more information and a list of language JAR files, see e.Reporting for Multiple Locales. (optional) Include this JAR file in projects in which you want the e.Spreadsheet Designer to provide access to textures for filling drawing objects.

f1jtextures.jar

Using the e.Spreadsheet API


This chart shows the primary e.Spreadsheet classes and interfaces. They are organized into two groups: APIs for projects that have a graphical user interface (on the left), and APIs for projects that do not have a graphical user interface (on the right). The two main classes, com.f1j.swing.JBook and com.f1j.ss.BookModelImpl, provide the same functionality, except that BookModelImpl does not include the code required for working with a GUI.

10

Programming e.Spreadsheet Reports

Chapter 1, Programming with e.Spreadsheet

11

e.Spreadsheet packages
e.Spreadsheet is divided into the following packages, all of which make up the public API and are available in f1j9swing.jar. Package Name com.f1j.addin Description This package contains the abstract class Func, which can be extended to create custom worksheet functions that can be accessed from the spreadsheet. This package contains the Database class, which enables data extraction from one part of a spreadsheet to another. This package contains the charting API to dynamically create and alter e.Spreadsheet charts. These packages contain the external data connection API for dynamically creating data sourcec, data queries, and spreadsheet data ranges. This package contains an applet class that allows developers to share spreadsheet data within the context of a browser using the InfoBus technology. The infobus.jar file must be available for compiling code that references this package. Primary Classes Func

com.f1j.calc

Database

com.f1j.chart

ChartModel

com.f1j.data.*

DataRangeImpl

com.f1j.infobus

InfoBusBook

com.f1j.mvc

This package contains the Constants base interface for a model in Model e.Spreadsheets model-viewcontroller architecture.

12

Programming e.Spreadsheet Reports

Package Name com.f1j.ss

Description This package contains UIgeneric classes to save spreadsheets as HTML, format cells, and access the spreadsheet model directly without using the JBook class. This package contains the Swing components of e.Spreadsheet. This packages Designer class displays the e.Spreadsheet Designer, a Swing-based application that provides Excel-like menus, toolbars, and dialogs for spreadsheet data entry and formatting. This package contains classes to display Swingbased dialog boxes to collect information from the user. This package contains the e.Spreadsheet exception class.

Primary Classes HTMLWriter CellFormat BookImpl SheetImpl BookModelImpl

com.f1j.swing

JBook JBookApplet ChartImageEncoder Designer

com.f1j.swing.designer

com.f1j.swing.ss

FormatCellsDlg, PageSetupDlg, etc. F1Exception

com.f1j.util

Chapter 1, Programming with e.Spreadsheet

13

e.Spreadsheet primary classes


These are the main classes used to create and deploy e.Spreadsheet worksheets in an application or applet. Class name com.f1j.swing.JBook Description Spreadsheet component. This class can be instantiated from an applet, servlet, or application, or can be used in a formbuilding development environment. This class provides methods for manipulating the spreadsheet contents. e.Spreadsheet Designer. This Java application provides menus, toolbars, and dialogs on top of the com.f1j.swing.JBook spreadsheet component to help the user create, modify, and format spreadsheet files.

com.f1j.swing.designer.Designer

e.Spreadsheet utility classes


These classes can be used to write out HTML files from spreadsheets and to enable JDBC database connectivity. Class name com.f1j.ss.HTMLWriter com.f1j.ss.XMLWriter com.f1j.swing.ChartImageEncoder Description This class provides static methods to convert a worksheet to an HTML table. This class provides methods to convert worksheet ranges to XML. This class creates images and imagemaps from charts, generally for use in servlets. This class is used to specify the locale under which you want the e.Spreadsheet Designer to run.

com.f1j.util.Group

14

Programming e.Spreadsheet Reports

e.Spreadsheet Classes returned from JBook


The JBook class returns these classes. Class name com.f1j.ss.BookImpl Description This is the model portion of the JBook class. Developers can use this class to bypass the JBook methods when building the spreadsheet model. This class is used to set/get formatting information from the spreadsheet cells. These two classes represent the graphical objects on the spreadsheet. This class contains information regarding the last find/replace operation called. This class represents the custom formats stored in the spreadsheet. This class represents a range of cells. This class represents a cell.

com.f1j.ss.CellFormat com.f1j.ss.GRObject com.f1j.ss.GRObjectPos com.f1j.ss.FindReplaceInfo com.f1j.ss.NumberFormat com.f1j.ss.RangeRef com.f1j.ss.CellRef

e.Spreadsheet Exception
The one exception class in the e.Spreadsheet API is com.f1j.util.F1Exception. It can be thrown from several method calls throughout the API.

e.Spreadsheet events and listeners


The table below lists e.Spreadsheet events and listeners. For more information about using e.Spreadsheet events and listeners, see ????? Events and Listeners com.f1j.swing.CancelEditEvent com.f1j.swing.CancelEditListener com.f1j.chart.ChartEvent com.f1j.chart.ChartListener com.f1j.swing.ChartViewEvent com.f1j.swing.ChartViewListener Description This event is fired when the user exits in-cell editing mode by pressing the Esc key. This event is fired when something in the chart model changes. This event is fired when something in the chart view changes.

Chapter 1, Programming with e.Spreadsheet

15

Events and Listeners com.f1j.swing.EndEditEvent com.f1j.swing.EndEditListener

Description This event is fired when the user exits in-cell editing mode by normal means (pressing Enter, using the arrow keys or mouse to move to another cell, etc.). This event is fired after the spreadsheet has completed its recalculation cycle. This event is fired when a hyperlink is activated. This event is fired when the spreadsheets data or formatting changes. This event is fired when the user interacts with a graphical object. This event is fired each time the cell selection changes. This event is fired when the user enters in-cell editing mode. This event is fired when the recalculation cycle is about to begin. This event is fired when the component has repainted the spreadsheet. This event is fired when a validation rule fails. This event is fired when the visible part of the spreadsheet changes (e.g. scrolling, tab selection, window resize, etc.)

com.f1j.swing.EndRecalcEvent com.f1j.swing.EndRecalcListener com.f1j.swing.HyperlinkEvent com.f1j.swing.HyperlinkListener com.f1j.swing.ModifiedEvent com.f1j.swing.ModifiedListener com.f1j.swing.ObjectEvent com.f1j.swing.ObjectListener com.f1j.swing.SelectionChangedEvent com.f1j.swing.SelectionChangedListener com.f1j.swing.StartEditEvent com.f1j.swing.StartEditListener com.f1j.swing.StartRecalcEvent com.f1j.swing.StartRecalcListener com.f1j.swing.UpdateEvent com.f1j.swing.UpdateListener com.f1j.swing.ValidationFailedEvent com.f1j.swing.ValidationFailedListener com.f1j.swing.ViewChangedEvent com.f1j.swing.ViewChangedListener

16

Programming e.Spreadsheet Reports

Using the e.Spreadsheet API constants


All of e.Spreadsheets constants are in the four Constants interfaces: Interface com.f1j.chart.Constants com.f1j.data.Constants com.f1j.mvc.Constants com.f1j.ss.Constants Contains Constants used by the ChartModel interface to create, format, and print charts. Constants used by the Data interface. Paper size constants. Constants used by most e.Spreadsheet API.

Importing any of these interfaces provides access the e.Spreadsheet constants it contains. Referring to an individual class provides access to all the constants within that class. See code examples below. Most e.Spreadsheet classes implement the com.f1j.ss.Constants interface. These constants are accessible through any e.Spreadsheet class that implements the com.f1j.ss.Constants interface.

Code Examples
Example 1: This example imports a constant from the com.f1j.ss.Constants interface.
jbook1.write("c:\\file\examplefile.vts", new com.f1j.ss.WriteParams(com.f1j.ss.Constants.eFileExcel97));

Example 2: This example imports a class-specific constant (eDropDown) from the GRObject class.
jbook1.addObject(com.f1j.ss.GRObject.eDropDown, col1, row1, col2, row2);

Example 3: This example imports constants from the com.f1j.swing.JBook class.


jbook1.write("c:\\file\examplefile.vts", new com.f1j.ss.WriteParams(com.f1j.swing.JBook.eFileExcel97));

Chapter 1, Programming with e.Spreadsheet

17

Using e.Spreadsheet as a JavaBean


Because e.Spreadsheet is a JavaBean, you can use it in a development environment to automatically generate much of your Java code. The e.Spreadsheet JavaBean can be used in Java development environments such as Symantecs Visual Cafe, Inprises JBuilder, Microsofts Visual J++, Oracles JDeveloper, and SilverStreams Application Server. When you add e.Spreadsheet to a form in a development environment, the development environment generates much of the code required to use the component. If you want to customize the appearance or behavior of a workbook, you will need to access the e.Spreadsheet API directly rather than depending on the development environment to do it for you automatically. The process of accessing e.Spreadsheets JavaBean functionality in an application varies slightly from one development environment to another. In most cases it consists of: 1 adding the JavaBean to your project 2 selecting the component and drawing the control on a frame or in a window When e.Spreadsheet is used as a JavaBean, only a small set of its API is available through the development environments windows and menu options. Most developers will find that they have to access other parts of the e.Spreadsheet API within the Java code to take advantage of e.Spreadsheets many features. For detailed instructions on adding the JavaBean to your development environment, see the f1j_ide.html file located in the download, on the CD, or on Actuates website at www.actuate.com.

Using add-in functions


Add-in functions are small Java classes that extend the capabilities of e.Spreadsheet. To implement an add-in function, create a class that extends com.f1j.addin.Func. The new class must: 1 include a static initializer that makes sure an instance of the function is created;
static { new MyConcat(); }

18

Programming e.Spreadsheet Reports

2 include a private constructor that allows only one instance to be created. In that constructor, you must call the superclass constructor and pass the name of the function, the minimum number of arguments, and the maximum number of arguments;
private MyConcat() { super("MyConcat", 1, 30); }

3 and override the evaluate method in com.f1j.addin.Func.


public synchronized void evaluate(com.f1j.addin.FuncContext fc)

In order to use the add-in function it must be included in your class path. Also note that add-in function names are case-sensitive.

Code Example
This code example creates an add-in function that concatenates text and demonstrates an efficient way of handling threading.
// Add-in functions must be derived from com.f1j.addin.Func public class MyConcat extends com.f1j.addin.Func { // Since we have a member that can change, we must worry about // thread safety. This one variable will be shared by all threads. StringBuffer m_accum = new StringBuffer(); // The static initializer assures that the one and only // instance of MyConcat is created and added to com.f1j.calc.Funcs // list of add-in functions. static { new MyConcat(); } // Make this private so that only the one instance is created. private MyConcat() { // we can allow 1-30 arguments super("MyConcat", 1, 30); } // Override the com.f1j.addin.evaluate(...) to do the work. // We must use the "synchronized" modifier to ensure that

Chapter 1, Programming with e.Spreadsheet

19

// a 2nd thread does not attempt to modify "m_accum" while we are // using it. public synchronized void evaluate(com.f1j.addin.FuncContext fc) { m_accum.setLength(0); int argCount = fc.getArgumentCount(); for (int ii=0; ii < argCount; ii++) { com.f1j.addin.Value val = fc.getArgument(ii); if (val.checkText()) { m_accum.append(val.getText()); } else { fc.setReturnValue(val.eValueInvalidValue); return; } } fc.setReturnValue(m_accum.toString()); }

Creating an add-in function with cell references and ranges


This more complex code example of an add-in function creates a different SUM function and shows some additional capabilities of add-in functions. The performance of this function will not match the performance of the function SUM, but demonstrates the general capabilities of add-in functions.

Code Example
public class MyDoSum extends com.f1j.addin.Func { // This static initializer guarantees that the instance of this // function is created and added to the list of add-in functions. static { new MyDoSum(); } // Make this private so that only one instance is created private MyDoSum() { // we can allow 1-30 arguments */ super("MyDoSum", 1, 30);

20

Programming e.Spreadsheet Reports

// any argument can be a reference (not just resolved to a "value") for (int ii = 1; ii < 30; ii++) setReferenceArgument(ii); } // Override the com.f1j.addin.evaluate(...) to do the work public void evaluate(com.f1j.addin.FuncContext fc) { int argCount = fc.getArgumentCount(); double sum = 0.0; //initialize the result for (int ii=0; ii < argCount; ii++) { com.f1j.addin.Value val = fc.getArgument(ii); if (val.isCell()) { com.f1j.ss.Sheet sheet = val.getSheet(); int cellType = Math.abs(sheet.getType(val.getRow1(),val.getCol1())); if (cellType == com.f1j.ss.Book.eTypeNumber) { sum += sheet.getNumber(val.getRow1(), val.getCol1()); } else if (cellType == com.f1j.ss.Book.eTypeError) { fc.setReturnValue(val.eValueInvalidValue); return; } } else if (val.isRange()) { com.f1j.ss.Sheet sheet = val.getSheet(); int row2 = val.getRow2(); int col2 = val.getCol2(); for (int i = val.getRow1(); i <= row2; i++) { for (int j = val.getCol1(); j <= col2; j++) { int cellType = Math.abs(sheet.getType(i, j)); if (cellType == com.f1j.ss.Book.eTypeNumber) { sum += sheet.getNumber(i,j); } else if (cellType == com.f1j.ss.Book.eTypeError) { fc.setReturnValue(errInvalidValue); return; } } } } else if (val.checkNumber()) { sum += val.getNumber(); } else { fc.setReturnValue(val.eValueInvalidValue);

Chapter 1, Programming with e.Spreadsheet

21

return; } } fc.setReturnValue(sum); }

Setting recalculation for add-in functions


Functions in e.Spreadsheet are either determinant or non-determinant. Determinant functions consistently return the same value from a given value and are not recalculated (e.g., ABS(n)). Non-determinant functions return values that may vary and are always recalculated (e.g., RAND()). By default, e.Spreadsheet assumes that add-in functions are non-determinant: formulas referring to these functions are always recalculated, even if the arguments to the function do not change. Calling the com.f1j.addin.Func.setDeterminant method overrides this default add-in function behavior, setting the add-in function to be determinant. Formulas referring to this function always return the same result given the same arguments and are not automatically recalculated. Calling the setDeterminant method can make a significant improvement in recalculation performance by setting e.Spreadsheet to not recalculate add-in functions with determinant results.

Getting the version number


Use either the getVersion or getVersionString method to return current version information.

Using the e.Spreadsheet Designer


1 Choose HelpAbout e.Spreadsheet... . The version number, build number, JDK Version, and other information are displayed.

Code Example
Example 1: This example returns the version information (version and build number, copyright notice, etc.) in a String format:
jbook1.getVersionString();

22

Programming e.Spreadsheet Reports

Example 2: This example returns the version information as an integer:


jbook1.getVersion();

Finding e.Spreadsheet demos and other help sources


Besides the manuals described in the introductory chapter, e.Spreadsheet includes several additional sources for help.

e.Spreadsheet-specific ReadMe files


Covering installation issues, known problems, details of Microsoft Excel compatibility issues, and late-breaking changes, the ReadMe file is available in text, PDF and Word formats. The files are found in the install_dir/help directory.

Tutorials
Two tutorials that explain by example how to use different parts of the e.Spreadsheet API. Tutorial 1 takes you through the process of building a Java application and shows basic e.Spreadsheet worksheet manipulation. Tutorial 2 shows how to create and format a chart using e.Spreadsheets charting API. Tutorials may be found in the install_dir/help/tutorial directory.

API Help.
Javadoc-generated guide to all of e.Spreadsheets public API. The API Help is available as Javadoc in the install_dir/help/awtdoc and install_dir/help/ swingdoc directories and as an HTML Help file in the install_dir/help/win directory.

Demos
e.Spreadsheet comes with several demos that developers can use to learn about the e.Spreadsheet API. Developers can use snippets of code from these demos to plug the demos functionality into their own applications. Each of the demos is located in a separate directory in the [installdirectory]\ examples\swing directory.

Chapter 1, Programming with e.Spreadsheet

23

Before running the demos, you must first compile them into class files using your development environments compiler or using the Java command-line compiler, javac. Then you can execute the resulting class within your development environment or from a command prompt using the Java command java. The demos are listed here by their directory names.

examples\swing\demos\amortization.
This demo shows how to use e.Spreadsheet in a simple web-based application. It converts spreadsheets to HTML or JPG files on the fly using servlet and page-compilation technology.

examples\swing\demos\calculate.
This page compilation demo shows how to call the JBook API from within a JHTML page. It displays a form and asks the user for a formula. That formula is passed to JBook, calculated, and returned to the user.

examples\swing\samples\add-in\blackscholes.
This demo shows how to write an add-in function that calculates the BlackScholes formula for determining the value of stock options.

examples\swing\samples\add-in\concat.
This demo shows two ways to handle threading issues in add-in functions. The demonstration functions concatenate strings.

examples\swing\samples\add-in\mydosum.
This demo shows how to write an add-in function that accesses a range of cells in a spreadsheet to perform a simple sum. It demonstrates how to handle cell references and ranges in an add-in function.

examples\swing\samples\apps\format.
This demo shows how to use the formatting API (specifically, the CellFormat object) to set borders, text colors, background colors, etc. The application displays several buttons next to a e.Spreadsheet worksheet. It formats the worksheet data differently based on the button pressed. This action is similar to the AutoFormat feature of Excel.

examples\swing\welcome.
This demo is the same as the code in Using the sample application and applet earlier in this chapter.Using the sample application and applet.

24

Programming e.Spreadsheet Reports

Chapter 1, Programming with e.Spreadsheet

25

26

Programming e.Spreadsheet Reports

Chapter

2
Chapter 2

Creating applications and applets

This chapter contains the following topics:


s s s s s s s s s s s s s

Resolving Java security issues Using digital signatures Using RSA verification and the Java 2 Plug-in Creating an RSA signed applet Converting Netscape signed applets to RSA signed applets Preparing an applet for Netscape Navigator Preparing an applet for Internet Explorer Setting Internet Explorer permission levels using the -jp option Checking CAB file permission levels Deploying signed applets Avoiding signing mistakes Reading, writing, and printing files from an applet Reading, writing, and printing files with no Plug-in

Chapter 2, Creating applications and applets

27

Resolving Java security issues


To read and write files from e.Spreadsheet with a browser, first you must resolve Java security issues found in browsers such as Internet Explorer and Netscape Navigator. Software developers and Webmasters must obtain their own digital signatures to enable their users to read and write files to and from their local disk or to print to a local printer.
s s

Digital signatures are not included among the e.Spreadsheet product files. Simply adding a worksheet to your Web pages does not require a digital signature. Digital signatures are required only when e.Spreadsheet needs to access system resources.

You can find more comprehensive information regarding Java security issues on-line at java.sun.com/security/index.html. Specific information about how the Java 2 Platforms security architecture works, differs from, and improves over previous versions of the JDK is available at java.sun.com/docs/books/ tutorial/security1.2/overview In developing applets for distribution over the Internet, developers must consider security issues arising from both the development environment and the browsers on which the applet will run. Java security issues work differently in the different versions of the Java development environment (JDK 1.0, 1.1 or Java 2). The Java 2 development environment adds several new security capabilities, including the option for both developers and users to set levels of security and improvements in the use of public and private keys, certificates and certification authorities. In general, the Java platforms security architecture prevents applets downloaded from a server from:
s s s s s s s s

reading or writing to your hard drive; accessing a printer, accessing the clipboard, connecting to another server; creating independent commands; loading a new dynamic library; defining native method calls; or starting other programs on your computer.

And, beyond Javas general security architecture, Java 2:

28

Programming e.Spreadsheet Reports

allows communication only between applets from the same Internet Protocol (IP) address, the same domain name and only on the same page gives users and developers the power to impose additional security measures or remove existing security restrictions using a system of security policies that defines access permissions within individual code domains.

Using digital signatures


Digital signatures, created through the use of a system of private keys, public keys, and certificates, provide the framework of Javas security structure. All three of these elements must be included in a JAR file to create a signed file that a user can download and use with some level of security.

Private Keys
A private key is a password-protected numeric code that identifies the individual sending the signed code or document. Private keys can be generated using Javas keytool or an API. To verify legitimacy, unmodified private keys match corresponding public keys to form a matching key pair.

Public Keys
A public key is a password-protected numeric code that identifies the entity generating the signed code or document. A public key always corresponds to a private key. Public keys can be verified by the use of Certificates and Certificate Authorities.

Certificates
A certificate contains a public key, information about the certified entity (entity name, organization, address), and a digital signature from (and information about) the issuer of the certificate. Various levels of security are possible using digital signatures. The simplest security level is to check whether the private and public keys correspond (whether they are a matching key pair) which can be further checked by contacting the issuer of the code or file containing the keys and verbally verifying the signatures. The use of certificates generated by third-party Certificate Authorities adds another level of security. Certificate Authorities firms that specialize in digital security (such as Verisign) issue certificates signed with their own private key which, in turn, verify that you are the owner of your public key. The Java 2 Development Platform adds capabilities to the Java Security Architecture through the use of policies, permissions and domains. Policies create the capability of setting your own security policies (such as not allowing

Chapter 2, Creating applications and applets

29

system access to code downloaded from sources without third-party certification). Permissions allow users to grant applets access to system components and other permissions based on the level of security. Files with the same permissions are enclosed in the same domain and have been downloaded from the same source. Downloaded applets and applications run in their own domain based on this combination of policies, permissions, and domains.

Using RSA verification and the Java 2 Plug-in


Using RSA verification with the Java 2 Plug-in presents several advantages over using browser-specific procedures:
s

Preparing an Applet for deployment works for both Netscape Navigator and Internet Explorer browsers. RSAs digital signature algorithm is used by Netscape Navigator, Internet Explorer and most other browsers and recognized across the Internet. RSA recognizes most common certificates, including Verisign and Thawte RSA certificates. RSA is used in the same way in all browsers, providing browserindependent signature verification. Users can validate signers and set security levels based on individual signers.

More information about RSA and using RSA Verification with the Java 2 Plugin is available online at www.rsasecurity.com and www.java.sun.com/ products/plugin/1.2/docs/nsobjsigning.html

Creating an RSA signed applet


Use the following directions to create an RSA signed applet from scratch. Use the procedure under Converting Netscape signed applets to RSA signed appletsConverting Netscape signed applets to RSA signed applets if you have an applet signed with an earlier version of signtool.exe that you would like to convert to work with the Java Plug-in. 1 Make sure you have:
s s s

Netscape Signing Tool. A Netscape Object Signing Certificate from an RSA Certificate A certificate from an independent Certificate Authority (CA) such as Belsign, Verisign or Thawte.

2 Install the Netscape Signing Tool if necessary. You can download the software from developer.netscape.com. Be sure to install the Netscape Signing Tool and the Object Signing Certificate in a secure location.

30

Programming e.Spreadsheet Reports

3 Create the applet by archiving the .class files into a JAR file using the jar command in the Java SDK. See instructions under Create a JAR file in Preparing an applet for Netscape Navigator later in this chapter.Preparing an applet for Netscape Navigator. 4 Use Netscape Signing Tool to sign the JAR file. The jar.exe program comes with most Java development environments (look in <install_dir>/bin).

Converting Netscape signed applets to RSA signed applets


JAR files signed using earlier versions of Netscape signtool.exe will not run properly in the Java Plug-in. Use the following procedure to convert them. 1 Delete or remove references to netscape.security.* from the applet. 2 Archive and sign following the instructions under steps 3. - 4. in Creating an RSA signed appletabove.

Deploying applets
Preparing an applet for Netscape Navigator
For Navigator, all of the applets classes must be contained in a JAR file created by appending the class files from the applet to the e.Spreadsheet JAR file, or decompressing the e.Spreadsheet class files and creating a new JAR file with the applet classes and a subset of the e.Spreadsheet classes. Regardless of the method used, for Navigator, digital signatures are applied to JAR files. For Netscape Navigator, information about your software publishing certificate and key are contained in two files: key3.db and cert7.db. When you obtain software publishing certificates and keys from signing authorities, certificate and key information is placed in these files. Typically, key3.db and cert7.db are located in the Netscape directory on your system. On Unix systems, if you dont already have a ~/.netscape directory, you can run Netscape Communicator to create the necessary directory structure. In Windows 95 and Windows NT, these files are typically located in \Program Files\Netscape\Users\Username. To prepare an applet for Netscape Navigator, follow these steps: 1 Create a JAR file using jar.exe:

Chapter 2, Creating applications and applets

31

a. Type and enter the following code from a command prompt:


jar -cvf c:\jar_name.jar class1.class class2.class

where: -cvf tells the program to create a verbose file jar_name.jar tells the program the output filename class1.class, class2.class tells the program to include these class files Be careful not to include directory names with the class file names. This adds directory names to the class files in the JAR file. Once placed on a web server, these files would not be found. a. If you want to include the e.Spreadsheet classes in the same JAR file you need to first unjar f1j9swing.jar using the following code:
jar -xvf c:\f1j9swing.jar

This unjars the JAR file into a subdirectory beginning with c:\com\f1j. a. Reference this subdirectory when adding it to the JAR file you want to sign.
jar -cvf c:\com\f1j\* class1.class class2.class

1 Sign the JAR file using signtool.exe. To sign a JAR file, you actually create a new signed JAR file. The applet JAR file you create can be digitally signed for Navigator with signtool.exe. You can find more information about Netscape Signing Tool and download signtool.exe from the Netscape website www.developer.netscape.com. a. Obtain a digital signature and key information from a signing authority (such as BelSign, Verisign, or Thawte). b. Find the nickname from your cert7.db signature file located in the Netscape directory on your system. c. At a command prompt type and enter:
signtool l

a. Use signtool.exe and the nickname in the command to create a new signed JAR file.
signtool.exe -k nickname -Z c:\newjarfilename.jar -d:\keys\ c:\ yourfiles_directory

32

Programming e.Spreadsheet Reports

where: -k nickname is the nickname of the certificate in the cert7.db file you found in step 1., -Z c:\newjarfilename.jar is the name of the JAR file you are signing, -d:\keys\ is the name of the directory in which cert7.db and key3.db are locatedthey must be the same keys used in the Program Files/ Netscape/Users/username directory), and c:\yourfiles_directory is the name of the directory that contains the JAR file. yourfiles_directory must contain your classes to JAR up. If you want the JAR file to include the e.Spreadsheet classes, unjar f1j9swing.jar into this directory as well.

Preparing an applet for Internet Explorer


For Internet Explorer, all of the classesincluding the classes for e.Spreadsheet and the classes created for the appletmust be packaged in a single CAB file. The CAB file is the file that receives the digital signature. To do this, extract the .class files from the JAR files and reassemble them into a CAB file using cabarc.exe. Finally, sign the new CAB file using signcode.exe. To prepare an applet for Internet Explorer: 1 Extract the class files from JAR files:
jar -xvf jarfile.jar

where: jarfile is the name of the file you want to decompress. The classes are decompressed and placed in the current directory. 2 Create a new CAB file using cabarc.exe. a. At a command prompt, type:
cabarc.exe -P -p \your_dir\ -r -s 6144 n cab_name.cab c:\your_dir\com\f1j\*.* + c:\your_dir\applet_classes.class

where: cab_name.cab is the name of the CAB file you are creating, -P strips the specified directory structure from the e.Spreadsheet classes and the other classes in the applet,

Chapter 2, Creating applications and applets

33

-p \your_dir\ preserves the path name to the directory, -r recurses the directories, and -s reserves space for digital signing. cabarc.exe creates a CAB file with the e.Spreadsheet classes and the applet classes you appended at the end of the command. b. If you want to include the e.Spreadsheet Java classes in the same CAB file, change the line to read:
cabarc.exe -p -P \your_dir\ -r -s 6144 n cab_name.cab c:\your-dir\com\f1j\*.* + c:\class1.class c:\class2.class

3 Sign the CAB file using signcode.exe. 4 Obtain a digital signature and key information from a certificate authority (such as BelSign, Verisign, or Thawte). a. At a command prompt, type: signcode.exe -j javasign.dll -jp low -spc myspecfile.spc v mypriv.pvk cab_name.cab where: -j tells the program to use Java permission, -jp sets the permission level for the CAB file, -spc myspecfile.spc specifies the name of the file that contains your software publishing certificate, -v mypriv.pvk is the name of the file that contains your private key information, and cab_name.cab is the name of the CAB file you are signing. Download the latest versions of signcode.exe and cabarc.exe from the Microsoft Developers Network website at msdn.microsoft.com/ downloads/sdks.

Setting Internet Explorer permission levels using the -jp option


The -jp option of the signcode.exe program allows you to set the permission level of the CAB file. Internet Explorer recognizes three permission levels: low, medium, and high. The following table describes how the permission

34

Programming e.Spreadsheet Reports

level assigned to an applet corresponds with the security settings in Internet Explorer: Applet permission set as

Internet Explorer security setting and action required by user when applet is downloaded: Low Medium Approval required None None High Approval required Approval required None None None None

Low Medium High

Checking CAB file permission levels


After signing the CAB file, you can check the permission information to make certain the file was created correctly using the chkjava.exe program provided with the Microsoft Internet Client SDK. To check permission levels, at the command prompt, type:
chkjava.exe cab_name.cab

where: cab_name.cab is the name of the CAB file you want to check.

Deploying signed applets


To deploy the signed applet, reference the JAR file from the HTML page using ARCHIVE = xyz.jar in the APPLET tag and copy the JAR file and HTML page to your web server. For more information, see Using the sample application and applet in Chapter 1, Programming with e.Spreadsheet.Using the sample application and applet.

Avoiding signing mistakes


The following list includes the most common signing errors and how to fix them.

Chapter 2, Creating applications and applets

35

Bad Magic Number error:


One of the class files is either corrupt or the syntax for signing the JAR file was wrong. Check to make sure all filenames and paths are correct and that the appropriate \ characters are present.

Cannot find a .class file:


Check the HTML code to make sure the files are in the correct directory. Also make sure the .class file is in the JAR or CAB file and does not include a path name (like c:\F1Java) as part of the file name.

Security errors:
Either the file is not properly signed or you have not included the extra PrivilegeManager information for Netscape in your code.

Cannot find javasign.dll:


Javasign.dll is a supporting file for signcode.exe and must be in the same directory. Internet Explorer 5 recognizes both CAB and JAR files. If you are using your own CLASS file, include it in the signed archive file (as explained in Preparing an applet for Internet Explorer on page 33).

Reading, writing, and printing files from an applet


To read, write, or print files with an applet from or to the users local machine, your JAR or CAB file must be digitally signed. If you use a .class file (as opposed to JavaScript) to access the read, write, or filePrint methods, this file should be part of the signed archive file.

Reading, writing, and printing files with no Plug-in


In order for reading, writing, and printing to work in Netscape without using the Plug-in, you must download the Capabilities API Classes from developer.netscape.com This is a zip file that you must unzip and then include in the signed archive file. In your program file, you need to add the following import statement:
import netscape.security.*;

Before the call to the filePrint method, you need to add this line:
PrivilegeManager.enablePrivilege("UniversalPrintJobAccess");

36

Programming e.Spreadsheet Reports

Before the call to the read method, you need to add this line:
PrivilegeManager.enablePrivilege("UniversalFileRead");

Before the call to the write method, you need to add this line:
PrivilegeManager.enablePrivilege("UniversalFileWrite");

Developing applications
Creating a simple application
The simple code example below illustrates the minimal code needed to create an application that displays a worksheet, accesses the API, and places a text string in a worksheet cell. The HTML needed to add and display the applet on a web page is included below the code example. For a more sophisticated example, see Using the sample application and applet in Chapter 1, Programming with e.Spreadsheet.Using the sample application and applet.

Code Example
For this example to run properly, the swing library, swingall.jar must be on the class path. For information about changing class path, see Changing the class path on my machine later in this chapterChanging the class path on my machine.
import java.awt.*; import com.f1j.swing.*; public class SimpleApp extends javax.swing.JFrame { public SimpleApp() { // Setup JFrame getContentPane().setLayout(null); setSize(450, 275); setBackground(java.awt.Color.lightGray); setTitle("Simple Application"); // Create a new instance of e.Spreadsheet com.f1j.swing.JBook jbook1 = new com.f1j.swing.JBook();

Chapter 2, Creating applications and applets

37

// Set the size of the e.Spreadsheet jbook1.setBounds(10, 5, 400, 200); // Add e.Spreadsheet to the JFrame getContentPane().add(jbook1); // Call the e.Spreadsheet setText API to place text in a cell try { jbook1.setText(2, 0, "Welcome to e.Spreadsheet: "); } catch (com.f1j.util.F1Exception e) { } // Add a window listener to handle the window closing SimpleWindow sWindow = new SimpleWindow(); addWindowListener(sWindow); } static public void main(String args[]) { // This is the starting point for the application // Create an instance of our SimpleApp frame and show it (new SimpleApp()).setVisible(true); } class SimpleWindow extends java.awt.event.WindowAdapter { // The window closing event was captured public void windowClosing(java.awt.event.WindowEvent event) { // The window closing event coming from the SimpleApp frame Object object = event.getSource(); if (object == SimpleApp.this) SimpleApp_WindowClosing(event); } } void SimpleApp_WindowClosing(java.awt.event.WindowEvent event) { setVisible(false); // Hide the JFrame dispose(); // Free the system resources System.exit(0); // Close the application } }

38

Programming e.Spreadsheet Reports

Changing the class path on my machine


You do not have to modify your systems class path to install or run e.Spreadsheet. However, certain situations may require that you manually change your systems class path settings, including:
s s s

Running e.Spreadsheet on other than the default virtual machine Troubleshooting errors including messages about missing java-specific files Specifying which JAR files to run when running a limited version of e.Spreadsheet Clearing leftover settings from earlier versions of software.

Instructions are provided below for changing class path on Windows 95/98/ NT/2000, and UNIX operating systems. Changing the class path environment startup settings saves the changes in the system settings. Changing settings using the JVMs -classpath option changes the settings for the current session only.

Changing the class path on Windows 2000


1 Choose Start Settings Control Panel to display the Control Panel window. 2 Double-click the System icon to open the System Properties dialog. 3 Select the Advanced tab. 4 Select the CLASSPATH variable in the User variables pane. 5 Select Edit. 6 If you want to use f1j9swing.jar, add the following path to your class path:
<install-dir>\f1j9swing.jar

7 Add any other JAR files needed to run e.Spreadsheet or delete any unneeded files. 8 Choose Set. 9 Choose OK.

Changing the class path on Windows NT 4.0


1 Select Start Settings Control Panel to display the Control Panel window. 2 Double-click on the System icon to display the System Properties dialog.

Chapter 2, Creating applications and applets

39

3 Select the Environment tab. 4 Select CLASSPATH in the User Variables list. (You may need to create the CLASSPATH variable using the variable and value frames.) 5 If you want to use f1j9swing.jar, add the following path to your class path:
<install-dir>\f1j9swing.jar

6 Add any other JAR files needed to run e.Spreadsheet or delete any unneeded files. 7 Choose Set. 8 Choose OK.

Changing the class path on Windows 95 or Windows 98:


1 Edit the autoexec.bat file located in your root directory. 2 Look for the set command 3 If you are using f1j9swing.jar, add the following path to your CLASSPATH:
<install-dir>\f1j9swing.jar

4 Add any other JAR files needed to run e.Spreadsheet in a limited mode or delete any unneeded files. 5 Save the autoexec.bat file. 6 Reboot the computer.

Changing the class path on UNIX or Solaris Machines:


1 If you are using f1j9swing.jar, at the command prompt, add the following path:
$ set CLASSPATH = $CLASSPATH: <install-dir>/f1j9swing.jar $ export CLASSPATH

2 Add any other JAR files needed to run e.Spreadsheet or delete any unneeded files.

Using the JVM -classpath option


This is the recommended method for changing class path settings since each application uses the class path it needs without interfering with other applications. Further information about class path variables and their use in

40

Programming e.Spreadsheet Reports

the Java development environment is available on the Internet at http:// java.sun.com//products/jdk/1.2/docs/tooldocs/win32/classpath.html. Java and JDB tools have a -cp (an abbreviation of class path) option, used in the example below.

Chapter 2, Creating applications and applets

41

Changing the JVMs class path on any Platform from a Command Prompt:
1 Switch to the directory that contains e.Spreadsheet (for example, c:\ F1Java): 2 Execute the following command:
java -cp f1j9swing.jar com.f1j.swing.designer.Designer

Or Execute the following command to include the JavaHelp documentation:


java -cp f1j9swing.jar;jh.jar;F1Help.jar com.f1j.swing.designer.Designer

On Unix machines, replace the semicolons (;) with colons (:).

42

Programming e.Spreadsheet Reports

Adding a message box


Use the messageBox method to create a message box. This method displays a message in a dialog box, waits for the user to click a button, and returns an integer indicating which button the user clicked.

Syntax
public int messageBox(java.lang.String message, java.lang.String caption, short type)

Parameters
Parameter message caption type Returns: Description The text displayed in the message box. The text displayed in the title bar of the message box. The sum of values specifying the number and type of buttons to display in the message box. One of the following integers indicating the button the user clicked in response: Integer Returned 1 2 User Clicked OK CANCEL Description Allows the user to acknowledge and accept the message. Allows the user to acknowledge the message but dismiss the message box without performing any action. An affirmative response to the question in the message. A negative response to the question in the message.

4 8

YES NO

Code Example
jbook1.messageBox("Test Message", "caption", (short) (jbook1.YES |jbook1.NO)); jbook1.messageBox("Test Message", "caption", (jbook1.OK));

The YES and the NO options cannot be used individually; they have to be ORed.

Chapter 2, Creating applications and applets

43

44

Programming e.Spreadsheet Reports

Chapter

3
Chapter 3

Listening for events

This chapter contains the following topics:


s s s s s s s s s

Finding out whether a worksheet has been modified Finding out whether the user is in edit mode Getting the most recent data entry Finding out which key the user pressed Finding out when a user changes from one cell to the next Finding out when a user changes worksheets Maintaining cell format when the user enters a value Canceling what the user enters in a cell Converting pixels returned from a mouse event to twips

Chapter 3, Listening for events

45

Finding out whether a worksheet has been modified


To find out whether a worksheet has been modified: 1) Define a global variable and initialize it to false; 2) Set the flag to true in the ModifiedEvent handler.

Code Example
void modified(ModifiedEvent e) { m_modified = true; }

Finding out whether the user is in edit mode


To find out whether the user is in edit mode, first define a global variable, then set the variables to true in the StartEditEvent object, false in the CancelEditEvent object, and false in the EndEditEvent object.

Code Example
The following code assumes that your class is implementing the StartEditListener, EndEditListener, and CancelEditListener interfaces.
boolean isInEditMode; //global variable jbook1.addCancelEditListener(this); jbook1.addEndEditListener(this); jbook1.addStartEditListener(this); public void startEdit(com.f1j.swing.StartEditEvent startEditEvent) { isInEditMode = true; } public void endEdit(com.f1j.swing.EndEditEvent endEditEvent) { isInEditMode = false; } public void cancelEdit(com.f1j.swing.CancelEditEvent cancelEditEvent) { isInEditMode = false; }

46

Programming e.Spreadsheet Reports

Getting the most recent data entry


To get the most recent data entered, create an EndEditListener, then use the endEdit and getEditString method to return the data entered.

Code Example
jbook1.addEndEditListener(this); public void endEdit(com.f1j.swing.EndEditEvent edit) { edit.getEditString(); }

Finding out which key the user pressed


To monitor key presses, set up a KeyListener then capture the KeyEvent using the keyPressed and keyReleased methods. Note that this will not capture text input after entering edit mode.

Code Example
jbook1.addKeyListener(this); public void keyPressed(KeyEvent e1) { try { jbook1.setText(0, 0, e1.getKeyText(e1.getKeyCode())); } catch (com.f1j.util.F1Exception e2) { } } public void keyReleased(KeyEvent e1) { try { jbook1.setText(0, 0, e1.getKeyText(e1.getKeyCode())); } catch (com.f1j.util.F1Exception e2) { } }

Chapter 3, Listening for events

47

Finding out when a user changes from one cell to the next
To monitor when a user changes cells, set up a SelectionChangedListener.

Code Example
jbook1.addSelectionChangedListener(this); public void selectionChanged(com.f1j.swing.SelectionChangedEvent e) { try { jbook1.setText(0, 0, jbook1.getRow() + "," + jbook1.getCol()); } catch (com.f1j.util.F1Exception e) { } }

Finding out when a user changes worksheets


To monitor whether a user has changed sheets, establish a value for the current sheet, then use the selectionChanged method to compare the new sheet to the current sheet.

Code Example
currentSheet = jbook1.getSheet(); public void selectionChanged(com.f1j.swing.SelectionChangedEvent e1) { int newSheet = jbook1.getSheet(); if (newSheet != currentSheet) { currentSheet = newSheet; } }

Maintaining cell format when the user enters a value


When the user enters a number into a cell, e.Spreadsheet guesses at the type of data entered by looking at the datas form. If the user enters data in the form of a date (e.g. 12/1/99) in a cell formatted numerically (e.g. #,###0.00), the

48

Programming e.Spreadsheet Reports

format is changed to a date format automatically. If this is not desired, you can use the EndEditListener interface to watch for changes to the cell and then reapply the original formatting during the EndEdit event.

Code Example
public void endEdit(com.f1j.swing.EndEditEvent edit1) { try { // See if the edited cell is in the formatted range. if (jbook1.getActiveCell().getRow() <= 5 && jbook1.getActiveCell().getCol() <= 5); // Reset the cell value format. jbook1.setCellFormat(specialFormat); } catch (com.f1j.util.F1Exception e1) { } }

Canceling what the user enters in a cell


To not allow the user to leave edit mode, but preserve what they have typed so far, use the endEdit method and pass true to the setCanceled method. To allow the user to leave edit mode but cancel what they have typed, use the endEdit method with the cancelEdit method.

Code Example
Example 1: This example allos the user to leave edit mode, but preserves what they have typed.
public void endEdit(EndEditEvent e) { e.setCanceled(true); }

Example 2: This example allows the user to leave edit mode but cancels what they have typed.
public void endEdit(EndEditEvent e) { jbook1.cancelEdit(); }

Chapter 3, Listening for events

49

Converting pixels returned from a mouse event to twips


There are 1440 twips to an inch, so to convert pixels to twips, create code that converts pixels based on the current screen resolution to twips as shown in the code example below.

Code Example
public void mouseClicked(MouseEvent e) { int logPixels = java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); int twipsX = e.getX() * 1440 / logPixels; int twipsY = e.getY() * 1440 / logPixels; com.f1j.ss.CellRef cellRef = jbook1.twipsToRC(twipsX, twipsY); }

50

Programming e.Spreadsheet Reports

Chapter

4
Chapter4

Increasing performance

This chapter contains the following topics:


s s s s s s s s s

Finding out maximum length of a worksheet formula Finding out the maximum number of characters in a cell Using memory efficiently Getting and releasing locks Understanding data structure and memory size Allocating row and column references Increasing or decreasing garbage collection Maintaining speed when reading in large amounts of data Finding out why e.Spreadsheet uses memory even when it seems that nothing is happening

Using memory efficiently


To make the most efficient use of memory and get the best performance from e.Spreadsheet:

Use only the files required to add the specific functionality needed in your application
This can substantially reduce file size, which in turn reduces download times. For more information, see Reducing applet and JavaBean size for use over the

Chapter 4, Increasing performance

51

Internet in Chapter 13, Deploying on the Web.Reducing applet and JavaBean size for use over the Internet.

Use getLock and releaseLock


The getLock method locks all views and workbooks for the current group so that no other thread will be allowed to access them until the releaseLock method is called. Lock a book before performing multiple related actions in order to improve performance and ensure consistency. For more information, see Getting and releasing locks later in this chapterGetting and releasing locks.

Build worksheets by rows rather than columns


In e.Spreadsheet memory is allocated by rows. You can save memory by building worksheets a row at a time, rather than a column at a time. For example, fill cells in row 1 before moving to row 2, and so on, rather than filling cells in column A before moving to column B, and so on.

Avoid formatting blank cells


When you format a blank range that does not consist of whole rows or whole columns, e.Spreadsheet must create empty cells before applying formats. For more information, see Understanding data structure and memory size later in this chapterUnderstanding data structure and memory size.

Build ranges from the lower right-hand corner


When building a table one cell at a time using code, starting in the lower right corner of the area in which you are working is faster and more efficient. This ensures that the row references are allocated simultaneously instead of one at a time. Likewise, each row is allocated once instead of reallocated each time a cell is added. For more information, see Allocating row and column references later in this chapter.Allocating row and column references.

Use values instead of formulas whenever possible Avoid adding empty rows and columns for white space
Adjust the row height or column width to create white space instead of adding empty rows or columns. If you must add empty rows or columns, empty rows are more efficient.

Disable repainting when performing a series of operations


When performing a number of sequential operations on a worksheet, disable repainting with setRepaint so the screen does not repaint after each operation.

52

Programming e.Spreadsheet Reports

This increases the speed of the operation and avoids unnecessary screen flashing.

Use methods to copy and move data


Use the editCopyRight, editCopyDown, copyRange, and moveRange methods to copy and move cells. These methods are much faster than using the clipboard. In addition, these methods update cell references to maintain the integrity of your formulas.

Getting and releasing locks


The getLock method locks all views and workbooks for the current group so that no other thread will be allowed to access them until releaseLock is called. Most methods and properties in the e.Spreadsheet API call getLock and releaseLock internally. Calls to getLock may be nested, but releaseLock must be called once for each getLock. Typically, getLock should be used in the following fashion:
jb.getLock(); try { ... } finally { jb.releaseLock(); }

A view should be locked before performing multiple related actions. This will ensure consistency and improve performance. Increases in performance from using the getLock and releaseLock methods are highest on dual processor machines with improved speeds up 26 times faster than processes not using the getLock and releaseLock methods. On single processor machines, the time savings is not as impressive (about 1.5 times faster), but still valuable.

Chapter 4, Increasing performance

53

Allocating row and column references


Where possible, fill the sheet by rows instead of columns. An array of row references is allocated for each row with data. For each allocated row, e.Sprteadsheet allocates an array of column references. Rows without data have only a row reference, not an array of column references for that row. Load the sheet from bottom right to top left. Since e.Spreadsheet allocates row and column references based upon the last row or column containing data, loading the sheet from bottom right to top left increases efficiency by allowing e.Spreadsheet to allocate the entire array of row and column references before filling the sheet. Once these arrays are allocated, e.Spreadsheet only has to allocate space (not references) for each cell. Loading the worksheet the opposite way, from top left to bottom right, means that the arrays of row and column references must grow as the number of rows and columns grows. Each time these arrays need to grow, e.Spreadsheet must allocate a new array. This leads to increased garbage collection (memory re-allocation) and decreased speed. Pre-allocate the arrays by putting a value in the lower right corner of the expected range. This pre-allocates the row references. In order to pre-allocate all the arrays of column references, load a value into every cell in the column on the right of the range (especially recommended in worksheets with a large number of columns). After loading data into the worksheet, delete the data in these pre-loaded cells. The worksheet then re-evaluates the amount of memory it needs and returns the remaining memory. This decreases load times considerably.

Increasing or decreasing garbage collection


The gc method performs garbage collection on formatting and/or formula information associated with a workbook. Workbooks have resources associated with them that are not garbage collected after every change to a workbook. These resources are broken up into formatting information and formula information. As a general rule, resources associated with formatting are garbage collected only when a workbook is saved, whereas formula information is normally garbage collected by a background thread after recalculation is complete and when a workbook is saved. This normal operation has proven to be more than adequate for most interactive use. In some circumstances it might be necessary to call the gc method from time to time to keep e.Spreadsheet from keeping too much of this stale information around.

54

Programming e.Spreadsheet Reports

If you are using com.f1j.ss.BookImpl directly (as you might in a server environment) or if your application never writes out a workbook to a workbook format (Excel or e.Spreadsheet), there is no background thread cleaning up the formula information. If your application is making many dynamic changes of a non-repetitive nature to formulas, defined names or workbook formatting (e.g., cell formats, fonts, and validation rules), you will probably need to call Book.gc(false, true) from time to time to return non-used memory to the system. Because all workbooks within a group share one set of formula information, this operation garbage collects formula information for all workbooks in a group. Saved workbook files never contain stale formatting or formula information. Initializing a workbook or reading a new workbook into a workbook always forces garbage collection to occur.

Syntax
public void gc(boolean collectFormats, boolean collectFormulas)

Parameters
Parameter collectFormats collectFormulas Description Call with true to do garbage collection on formatting information. Call with true to do garbage collection on formula information for all workbooks in the same group as the specified workbook.

Understanding data structure and memory size


Basic Data Structure
There are three basic parts to an e.Spreadsheet data structure: row references, cell references, and cells.

Row References
The row reference array is a contiguous block of memory containing one object reference for each row. The size of an object reference is dependent on the

Chapter 4, Increasing performance

55

implementation of the JVM. Using JDK 1.3 SE on Windows 2000, each reference requires 4 bytes. So, for example, in a spreadsheet with10 rows, the row reference array contains 10 references of 4 bytes each in this implementation. As you add rows, this array expands.

Cell References
Each non-blank row consists of an array of cell references large enough to point to the last cell in a row. The cell reference array is a contiguous block of memory containing one 4-byte reference for each cell. So, if the last cell in a row is located in column H (the eighth column), that row contains eight 4-byte references (for columns A through H).

Cells
The cells themselves are small data structures containing the cells contents. The structures include a cells value, its format, its formula, its font, its alignment, and other cell attributes. Cells only exist in memory if they contain formulas or data or are formatted differently from the row or column in which they are located.

Code Example
The code example below outputs the number of bytes per reference for the JVM and platform it is run on.
public static void main(String[] args) { try { java.lang.Runtime rt = java.lang.Runtime.getRuntime(); long beforeGCFreeMemory = rt.freeMemory(); long beforeGCTotalMemory = rt.totalMemory(); long beforeGCUsedMemory = beforeGCTotalMemory - beforeGCFreeMemory; for (int i = 0; i < 10; i++) { // Give the JVM opportunity to garbage collect System.gc(); Thread.sleep(1000); } long startFreeMemory = rt.freeMemory(); long startTotalMemory = rt.totalMemory(); long startUsedMemory = startTotalMemory - startFreeMemory; Object[] o = new Object[10000000]; long endFreeMemory = rt.freeMemory(); long endTotalMemory = rt.totalMemory(); long endUsedMemory = endTotalMemory - endFreeMemory; System.out.println(" beforeGC Free: " + beforeGCFreeMemory + " total: " + beforeGCTotalMemory + " used: " + beforeGCUsedMemory); System.out.println(" start Free: " + startFreeMemory + " total: "

56

Programming e.Spreadsheet Reports

+ startTotalMemory + " used: " + startUsedMemory); System.out.println(" end Free: " + endFreeMemory + " total: " + endTotalMemory + " used: " + endUsedMemory); System.out.println("Apparent # of bytes per reference: " + ((endUsedMemory - startUsedMemory) / 10000000.0)); } catch (Throwable e) { System.out.println("main() got exception e=" + e); e.printStackTrace(); } System.exit(0); }

Recalculating using setAutoRecalc


To recalculate automatically, call the setAutoRecalc method with true. Use the recalc method to perform a one-time recalculation. Use the forceRecalc method to set all cells containing formulas in a workbook to be marked as needing to be recalculated. The setAutoRecalc method is set to true by default.

Using the e.Spreadsheet Designer


To turn on Automatic Recalculation: 1 Choose ToolsOptions. 2 Select the Calculation tab. 3 Select Automatic Recalc. To perform a one-time recalculation: 1 Press F9 or choose ToolsRecalc.

Code Example
try { jbook1.setAutoRecalc(true); // or jbook1.recalc(); // or

Chapter 4, Increasing performance

57

// forceRecalc can only be called in the Book interface or BookImpl class book1.forceRecalc(); } catch (com.f1j.util.F1Exception err) { }

Maintaining speed when reading in large amounts of data


The getEntry() and getEntry(int row, int col) methods have to process the data read from a worksheet to interpret whether the data is in the form of formulas, data, numbers, or text. If the data read in is text only (or formulas only or numbers only), then using the method that returns only that type of data (e.g., getText, getFormula, getNumber) will improve performance over using the getEntry method.

58

Programming e.Spreadsheet Reports

Finding out maximum length of a worksheet formula


For internal worksheet functions, the formula can have a maximum length of 1024 characters. There can be up to 30 comma-delimited parameters (arguments) in one formula. For example:
=Average(A1, B2, C3, D4, E5, F6,. . .) =Sum(A1:A10, B20, C40:H40,. . .)

Finding out the maximum number of characters in a cell


The current version of e.Spreadsheet can contain up to 32,767 characters per cell.

Finding out why e.Spreadsheet uses memory even when it seems that nothing is happening
The e.Spreadsheet program has a background thread that appears to use a lot of processor time when there is not actually much going on in the system. This background thread is set to a very low priority and will not ordinarily have a significant impact on system performance.

Chapter 4, Increasing performance

59

60

Programming e.Spreadsheet Reports

Part

2
Part 2

Working with cells

Part 2, Working with cells

61

62

Programming e.Spreadsheet Reports

Chapter

5
Chapter 5

Manipulating cells

This chapter contains the following sections:


s s s s s s s s s

General topics Sorting Restricting user access Accessing cell content Clearing, cutting, and deleting Copying and pasting Data entry using code Working with ranges Odds and ends of Working with cells

Chapter 5, Manipulating cells

63

Inserting cells using code


The insertRange method moves a specified range of cells to a specified new location and inserts a new group of cells, rows, or columns.

Syntax
public void insertRange(int row1, int col1, int row2, int col2, short shiftType)

Parameters
Parameter row1 col1 row2 col2 shiftType eShiftHorizontal eShiftVertical eshiftRows eShiftColumns Description Range starting row. Indexed from top to bottom beginning with 0. Range starting column. Indexed from left to right beginning with 0. Range ending row. Range ending column. Determines how the range cells should be shifted: Shifts cells horizontally beyond the last column, one cell to the right. Shifts cells vertically beyond the last row, one cell up. Shifts all cells beyond the last row, up to the first deleted row. Shifts all cells beyond the last column, to the left.

64

Programming e.Spreadsheet Reports

Parameter eFixupPrepend

Description (continued) Adds cells to the beginning (above or to the left) of the range. Prepended cells expand the range and are included in formulas and defined names that refer to the range. Note that eFixupPrepend and eFixupAppend must be used with one of the other shiftType constants. See Example 2, below. Adds cells to the end (below or to the right) of the range. Appended cells expand the range and are included in formulas and defined names that refer to the range. Note that eFixupPrepend and eFixupAppend must be used with one of the other shiftType constants. See Example 2, below.

eFixupAppend

Code Example
Example 1: This example inserts a range of cells beginning at row 0, column 2 (cell A3) and ending at row 13, column 2 (cell C12). Existing cells are shifted to the right.
try { jbook1.insertRange(0, 2, 13, 2, jbook1.eShiftHorizontal); } catch (com.f1j.util.F1Exception ie) { }

Example 2: This example appends 5 rows to a range of cells. If you had a defined name that referenced D2:D10, or had a formula such as =SUM(D2:D10) and you wanted to append 5 rows to the defined name or to the SUM range you could use the following code to do so. Note that eFixupPrepend and eFixupAppend must be used with one of the other shiftType constants: eShiftHorizontal, eShiftRows, eShiftVertical, and eShiftColumns.
try { // Select D10:D15 (5 rows) so that 5 rows will be appended jbook.setSelection(9, 3, 13, 3); jbook.editInsert((short)(jbook.eFixupAppend + jbook.eShiftRows)); } catch (com.f1j.util.F1Exception ie) { }

Chapter 5, Manipulating cells

65

Working with rows and columns


Selecting column or row headers
Use the setHeaderSelection method to select column or row headers using code.

Using the e.Spreadsheet Designer:


In the e.Spreadsheet Designer, press Ctrl+Shift and select the headers.

Syntax
public void setHeaderSelection(boolean topLeftHeader, boolean rowHeader, boolean colHeader)

Parameters
Parameter topLeftHeader rowHeader colHeader Description Boolean that specifies whether the cell at the intersection of the row and column headings is selected. Boolean that specifies whether the row headers are selected. Boolean that specifies whether the column headers are selected.

Code Example
This example selects the column headers and top left header.
jbook1.setHeaderSelection(true, false, true);

Getting row and column reference


These examples use the getSelection method to return the formula reference (e.g., B10:G25) of the selected cells.

Code Examples
Example 1:

66

Programming e.Spreadsheet Reports

This example returns the formula reference for the active selection. If more than one range is selected, this example returns a comma-delimited list of all active ranges.
String s = jbook1.getSelection();

Example 2: This example returns a RangeRef object for the selection chosen when multiple discontiguous selections have been made. If 5 is entered where there are only three selections, an exception is thrown. These are indexed beginning with 0 based on the order they were selected. In this example, for a single cell, m_iRow1 == m_iRow2, and m_iCol1 == m_iCol2.
RangeRef r = jbook1.getSelection(0); int m_iRow1 = r.getRow1(); // Returns first row of range int m_iRow2 = r.getRow2(); // Returns last row of range int m_iCol1 = r.getCol1(); // Returns first column of range int m_iCol2 = r.getCol2(); // Returns last column of range

Determining the last row or column containing data


There are six methods that return the last row or column containing data: Method getLastRow getLastCol getLastColForRow Description returns the last row containing a non-empty* cell. returns the last column containing a non-empty* cell. returns the index number of the last non-empty* column in the specified row.

* Non-empty cells include cells containing data, formatted cells, and cells with validation rules, regardless of whether they contain data. getLastDataRow getLastDataCol getLastDataColForRow returns the last row that contains data. return the last column that contains data. returns the index number of the last column in the specified row that contains data.

Chapter 5, Manipulating cells

67

Code Example
jbook1.getLastRow(); jbook1.getLastCol();

Preventing the setMinCol method from returning an invalid argument error


The setMinCol method returns the invalid argument error when you try to pass a number less than 0 or a number greater than youve passed with the setMaxCol method. Call the setMinCol method with the arg parameter, as shown in the code example, to avoid returning the error.

Code Example
jbook1.setMinCol(arg); // where 0 <= arg <= jbook1.getMaxCol()

68

Programming e.Spreadsheet Reports

Working with ranges


Getting the row and column coordinates using a defined named range
Set the setSelection method equal to the getDefinedName(Name) method where Name is a defined name in the workbook. Then use the getSelection method to return the coordinates.
try { int m_iRow1; int m_iRow2; int m_iCol1; int m_iCol2; jbook1.setSelection(jbook1.getDefinedName("Name")); com.f1j.ss.RangeRef range = jbook1.getSelection(0); m_iRow1 = range.getRow1(); m_iCol1 = range.getCol1(); m_iRow2 = range.getRow2(); m_iCol2 = range.getCol2(); } catch (com.f1j.util.F1Exception e1) { }

Totaling values in columns where number of rows varies


This example sums all the numbers from row 1 to the last row in each column from column A to the last column.

Code Example
int lastcol = jbook1.getLastCol(); int lastrow = jbook1.getLastRow(); for (int i = 0; i <= lastcol; i++) jbook1.setFormula(lastrow+2, i, "sum(" + jbook1.formatRCNr(0, i, false) + ":" + jbook1.formatRCNr(lastrow+2, i, false) + ")");

Chapter 5, Manipulating cells

69

Making named range values constant regardless of active cell pointer location
To make the values constant, make the references absolute using the $ symbol.

Using the e.Spreadsheet Designer


Set the values of defined names to be absolute (e.g., $F$4:$H$10) instead of relative (e.g., F4:H10).

Code Example
jbook1.setDefinedName("dn", "$F$4:$H$10"); // Use absolute references

Using the clearRange method


The clearRange method clears a specified range using row and column coordinate parameters and the same clearType parameters as the editClear method. The Sheet class version of the clearRange method clears the range without checking the protection status of cells within the range or for partial clearing of array entered formulas.

Syntax
public void clearRange(int row1, int col1, int row2, int col2, short clearType)

Parameters
Parameter row1 col1 row2 col2 Description Coordinate specifying the beginning row of the range. Coordinate specifying the beginning column of the range. Coordinate specifying the ending row of the range Coordinate specifying the ending column of the range

Rows are indexed from top to bottom beginning with 0; sheets and columns are indexed from left to right beginning with 0 clearType A constant specifying what is cleared:

70

Programming e.Spreadsheet Reports

Parameter

Description (continued) Constants eClearDlg eClearFormats eClearValues eClearAll Integer 0 1 2 3

Code Example
jbook1.clearRange(jbook1.getRow(), jbook1.getCol(), jbook1.getRow() + 100, jbook1.getCol() + 10, 3);

Copying a range from one sheet to another


The copyRange method copies within the same sheet or from one active sheet in a workbook to another active sheet in a different workbook.

Code Example
See Copying and pasting data on page 75.

Clearing, cutting, and deleting


Clearing cell contents
To clear cell contents from code, select the range you want to clear and call the editClear method. The editClear method clears all cells in the selected range and all selected objects on all selected worksheets. The method includes a clearType parameter that specifies what to clear using one of the constants listed in the table below.

Syntax
public void editClear(short clearType)

Chapter 5, Manipulating cells

71

Parameters
Parameter clearType Description A constant specifying what is cleared: Constants eClearDlg eClearFormats eClearValues eClearAll Integer 0 1 2 3

Code Example
jbook1.editClear(jbook1.eClearAll);

Clearing data only, leaving formatting


To clear data and leave the data formatting attached to the cell, use the editClear method to clear values only using the eClearValues parameter.

Syntax
public void editClear(short clearType)

Parameters
Parameter clearType Description A constant specifying what is cleared: Constant eClearDlg eClearFormats eClearValues eClearAll Integer 0 1 2 3

Code Example
jbook1.editClear(jbook1.eClearValues);

72

Programming e.Spreadsheet Reports

Using the editCut method


Like editClear, the editCut method clears the selected range and objects from the active worksheet, but editCut then adds the selected range or object to the clipboard. The editCut method does not include parameters indicating what to cut. The editCut method also cuts only a single selected range.

Code Example
jbook1.editCut();

Deleting unlocked cell contents after enabling protection


The default state for a cell is locked. The cell is not locked until protection is enabled for the entire worksheet. If you unlock the cell, e.Spreadsheet stores this as a format setting. Clearing all or formatting from the clear dialog clears the formatting and locks the cell. If protection is enabled for the worksheet, the cells are locked. Do one of the following to delete cell contents of locked cells from code: 1 Delete only the values of a cell to maintain their unlocked status. See code example below. 2 Use the Sheet class version of the clearRange method. The clearRange method from Sheet class clears the cell without regard to its protection status.

Code Example
try { jbook1.setEnableProtection(true); jbook1.clearRange(1, 1, 7, 1, jbook1.eClearValues); } catch (com.f1j.util.F1Exception ie) { }

Shifting remaining rows and columns after delete


The deleteRange method includes parameters for how remaining cells shift when cells are deleted.

Chapter 5, Manipulating cells

73

Syntax
public void deleteRange(int row1, int col1, int row2, int col2, short shiftType)

Parameters
Parameter row1 col1 row2 col2 Description Coordinate specifying the beginning row of the range. Coordinate specifying the beginning column of the range. Coordinate specifying the ending row of the range. Coordinate specifying the ending column of the range.

Rows are indexed from top to bottom beginning with 0; sheets and columns are indexed from left to right beginning with 0. shiftType A constant specifying how cells are shifted: Constants eShiftHorizontal eShiftVertical eshiftRows eShiftColumns Integer 1 2 3 4

Code Example
This code example deletes the range including rows 1-7 of column 1 and shifts the entire column over (deleting all cells in that column).
try { jBook1.deleteRange(1, 1, 7, 1, jbook1.eShiftColumns); } catch (com.f1j.util.F1Exception ie) { }

Copying and pasting

74

Programming e.Spreadsheet Reports

Copying and pasting data


The e.Spreadsheet API offers a number of ways to copy and paste data. The code example below uses the copyRange method. The articles listed below demonstrate other copying and pasting techniques:
s s

Pasting values only Maintaining protection on inserted ranges of cells when pasting in an unprotected range Importing large blocks of information Copying a range from one sheet to another Entering one value in all cells in a selected range Loading data from an array Using memory efficiently

s s s s s

Using the e.Spreadsheet Designer


1 Select the range to copy from the source workbook. 2 Choose EditCopy or press Ctrl+C. 3 Select either the top left cell of the destination range on the destination sheet or the entire destination range. 4 Choose Paste Special from the Edit menu or press Ctrl-V. 5 If Paste Special is chosen, a dialog appears allowing the choice of pasting Formulas, Values, Formats, or All.

Code Example
This code example assumes that two workbooks exist, jbook1 and jbook2. It will copy the data and formatting from the first 6 rows and columns of the first sheet of jbook1 to a new range on the first sheet of jbook2.
try { // Initialize variables int srcSheet=0, srcRow1=0, srcRow2=5, srcCol1=0, srcCol2=5; int dstSheet=0, dstRow1=2, dstRow2=7, dstCol1=2, dstCol2=7; jbook2.copyRange(dstSheet, dstRow1, dstCol1, dstRow2, dstCol2, jbook1, srcSheet, srcRow1, srcCol1, srcRow2, srcCol2, jbook1.eCopyAll); } catch (com.f1j.util.F1Exception err) { }

Chapter 5, Manipulating cells

75

Pasting values only


The editPasteSpecial method allows you to choose the type of data to paste: formulas only, values only, formats only, or any combination of types. To paste values only, call the editPasteSpecial method with a parameter of eCopyValues. This is useful when you want to paste values in a cell or range while maintaining the existing formatting information in the range.

Syntax
public void editPasteSpecial(short what)

Parameters
Parameter what Description What to pasteone or more of the following constants: Constant eCopyFormulas eCopyValues Description Copies formulas only. Copies existing values and results of formulas in sheet copied from. Copies formats only Copies all of the above Integer 1 2

eCopyFormats eCopyAll

4 7

Using the e.Spreadsheet Designer


1 Choose EditPaste Special. 2 Deselect everything but Values in the Paste frame. 3 Choose OK.

Code Example
jbook1.editPasteSpecial(JBook.eCopyValues);

Creating shortcut keys for copying and pasting


To make a copy and paste shortcut key: 1 Create a KeyListener. 2 In the KeyPressed event, check to see if the shortcut keys have been selected.

76

Programming e.Spreadsheet Reports

3 Call the editCopy or editPaste method. For more information about using listeners and events, see Chapter 3, Listening for events.Listening for events.

Code Example
public void jBook1_keyPressed(KeyEvent e) { try { if (e.getKeyCode()==(e.CTRL_MASK | java.awt.event.KeyEvent.VK_C)) { jbook1.editCopy(); } else if (e.getKeyCode()==(e.CTRL_MASK | java.awt.event.KeyEvent.VK_V)) { jBook1.editPaste(); } } catch (com.f1j.util.F1Exception fje) { } }

Selecting cells
Making multiple, non-contiguous selections
Use the setSelection method to select multiple ranges.

Using the e.Spreadsheet Designer


Hold down the Ctrl key while selecting the separate ranges.

Code Example
This code example selects three separate non-contiguous ranges.
jbook1.setSelection("A1, B2:B4, C5");

Locating the active cell using code


Using the twipsToRC method in combination with the methods getX, getY, getRow, and getCol will return the active cells position in coordinates.

Chapter 5, Manipulating cells

77

Code Example
public void mouseClicked(java.awt.event.MouseEvent event) { try { int logPixels = java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); int twipsX = event.getX() * 1440 / logPixels; int twipsY = event.getY() * 1440 / logPixels; com.f1j.ss.CellRef cRef = jbook1.twipsToRC(twipsX, twipsY); Integer inRow = new Integer(cRef.getRow()); Integer inCol = new Integer(cRef.getCol()); jbook1.messageBox(inRow.toString() +", "+ inCol.toString(), "", jbook1.OK); } catch (Exception me) { } }

Making the active cell visible


There are two different ways to give the active cell focus:
s

Use the showActiveCell method. If the active cell is not displayed in the visible portion of the window, showActiveCell repositions the window so that the active cell is visible. Use the setTopRow and setLeftCol methods to position the sheet to show the active cell.

Code Example
jbook1.showActiveCell();

Making the Enter key move the active cell to the next row by default
Call the setEnterMovesDown method to set a boolean flag to indicate whether the Enter key moves the active cell down.

Using the e.Spreadsheet Designer


1 Choose FormatSheetProperties to open the Format Sheet dialog. 2 Select the Edit tab. 3 Choose Enter Moves Down in the Enable options frame.

78

Programming e.Spreadsheet Reports

Code Example
jbook1.setEnterMovesDown(true);

Chapter 5, Manipulating cells

79

Restricting user access


Restricting editing to certain columns
To restrict editing by columns, check the column the user is in when the startEdit event fires, and then cancel the edit if the user is attempting to put text into a restricted column.

Code Example
// In the listener, make sure the user can only put data in the first 5 columns. public void startEdit(StartEditEvent e) { try { int m_iCol = jbook1.getActiveCol(); // If the user is in the restricted column, cancel edit mode. if (m_iCol > 4) e.setCanceled(true); } catch (com.f1j.util.F1Exception e) { } }

Restricting users to delete values and formatting


By default, using the Delete key deletes values only. To restrict users to deleting both values and formatting, set the setAllowDelete property to false, then use the KeyPressed event to trap the Delete keys keycode and perform the clear, passing eClearAll to the editClear method.

Code Example
First, pass false to setAllowDelete.
jbook1.setAllowDelete(false);

Then, enter the following code in the KeyPressed event:


try { if (e.getKeyCode()==e.VK_DELETE) jbook1.editClear(eClearAll); } catch (com.f1j.util.F1Exception e1) { }

80

Programming e.Spreadsheet Reports

Setting cell protection for a range, column, or row


By default, all worksheet cells are locked but not protected. Locking cells marks the cells for protection when protection is enabled.

Using the e.Spreadsheet Designer


To set protection for a range of cells: 1 Select the top left corner of the sheet to select all cells in the sheet. 2 Choose FormatCells to open the Format Cells dialog. 3 Select the Protection tab. 4 Unlock the entire sheet by deselecting Locked. 5 Select the desired column(s), row(s) or range(s) to lock. 6 Choose FormatCells again, select the protection tab, and select the Locked checkbox. 7 Choose FormatSheetEnable protection from the Format menu. 8 Choose OK.

Code Example
// Unlock cells. com.f1j.ss.CellFormat cf = jbook1.getCellFormat(); cf.setLocked(false); jbook1.setSelection(0, 0, jbook1.getMaxRow(), jbook1.getMaxCol()); jbook1.setCellFormat(cf); // Locks desired range and enables protection. cf.setLocked(true); jbook1.setCellFormat(cf, 0, 0, 3, 3); jbook1.setEnableProtection(true);

Maintaining protection on inserted ranges of cells when pasting in an unprotected range


Protection is either on or off for an entire worksheet. A range may be set to be protected or unprotected when the sheet is protectedso to paste a protected range within an unprotected range requires three procedures: 1 preparing a larger unprotected range; 2 protecting a smaller range, and; 3 preparing (enabling protection in) the worksheet.

Chapter 5, Manipulating cells

81

Use one of the parameters shown in the code examples when pasting the range.

Code Example
editPaste(jbook1.eCopyFormats); // Only paste the Format of the cell. editPaste(jbook1.eCopyAll); // Paste the Formula, Value and Format. editPaste(); // Paste the Formula, Value and Format.

Allowing users to select only unprotected cells


In the SelectionChangedEvent object, use the isLocked method to determine whether a cell is locked. If the cell is locked, move the selection to a predetermined cell, the next cell, or the previous cell.

Code Example
try { com.f1j.ss.CellFormat lock = jbook1.getCellFormat(); if (lock.isLocked() == true) jbook1.setActiveCell(1, 1); // This will move to Cell b2. You can substitute // the previous or next cell using variables. } catch (com.f1j.util.F1Exception e1) { }

Preventing users from entering data in locked cells without using cell protection
Enabling cell protection is the only option to prevent a user from entering data. Enabling protection applies to all locked cells (the default cell status). You can unlock cells prior to enabling protection to allow certain cells to be modified in a protected sheet.

Using the e.Spreadsheet Designer


To enable cell protection: 1 Choose FormatSheetEnable protection from the Format menu. To unlock cells: 1 Choose FormatCells to open the Format Cells dialog box. 2 Select the Protection tab. 3 Deselect the Locked check box. 4 Choose OK.

82

Programming e.Spreadsheet Reports

Code Example
Implement the com.f1j.swing.StartEditListener interface. Use the following lines to register and unregister the StartEditListener:
jbook1.addStartEditListener(this); // Add a StartEditListener jbook1.removeStartEditListener(this); // Remove a StartEditListener

Define the startEdit function in the StartEditListener interface as:


public void startEdit(com.f1j.swing.StartEditEvent event) { if (jbook1.getActiveRow() == 1 && jbook1.getActiveCol() == 1) // If a user tries to type in cell B2 . . . dont allow them to event.setCanceled(true); }

Limiting selection range to one cell


Add the following code to the SelectionChangedEvent object to limit the selection range to one cell.

Code Example
try { com.f1j.ss.CellRef m_mclSelection = jbook1.getActiveCell(); jbook1.setSelection(m_mclSelection.getRow(), m_mclSelection.getCol(), m_mclSelection.getRow(), m_mclSelection.getCol()); } catch (com.f1j.util.F1Exception e1) { }

Highlighting an entire row regardless of active cell location


The setRowMode method sets the row mode status. If called with true, the entire row is selected when the user selects a cell. If called with false, only one cell is selected.

Code Example
jbook1.setRowMode(true);

Chapter 5, Manipulating cells

83

Disabling drag-and-drop
Calling the setAllowMoveRange method with false effectively disables dragand-drop, making it unavailable to the user.

Using the e.Spreadsheet Designer


1 Choose FormatSheetProperties to open the Format Sheet dialog. 2 Select the Edit tab 3 Deselect Move Ranges by Dragging in the Allow User To frame. 4 Choose OK.

Code Example
This code prevents the user from moving a range.
jbook1.setAllowMoveRange(false);

Limiting characters users enter in a cell


To add a limit to the number of characters a user can enter, add an EndEditListener to your code and implement the endEdit method that sets a limit on character entry.

Using the e.Spreadsheet Designer


To limit the number of characters in cell A1 to fewer than 16: 1 Select cell A1. 2 Choose FormatCells to open the Format Cells dialog. 3 Select the Validation tab. 4 Type Len(A1) < 16 in the Rule: frame. 5 Choose OK.

Code Example
This code prevents the user from typing a string that has more than 15 characters. Implement the com.f1j.swing.EndEditListener interface, then use the following lines to register and unregister it:
jbook1.addEndEditListener(this); // Add an EndEditListener jbook1.removeEndEditListener(this); // Remove an EndEditListener

84

Programming e.Spreadsheet Reports

Define the endEdit function in the endEditListener interface as:


public void endEdit(com.f1j.swing.EndEditEvent event) { if (event.getEditString().length() > 15) jbook1.cancelEdit(); } // cancel the edit

Limiting visible rows and columns


Limit the number of visible rows and columns using the setMinCol, setMaxCol, setMinRow, and setMaxRow methods.

Using the e.Spreadsheet Designer


1 Choose FormatSheetProperties to open the Format Sheet dialog. 2 Select the View tab 3 Change the range in the Sheet Limits text box to the desired limits.

Code Example
jbook1.setMinCol(3); // Set minimum column seen to column D jbook1.setMinRow(4); // Set minimum row seen to row 5 jbook1.setMaxCol(5); // Set maximum column seen to column F jbook1.setMaxRow(6); // Set maximum row seen to row 7

Validating edit data from code


Validation can be performed within the endEditEvent object. In the example code below, code is added to cancel editing if a formula is not being entered.

Code Example
public void endEdit(com.f1j.swing.EndEditEvent e1) { if (! e1.getEditString().startsWith("=")) jbook1.cancelEdit(); }

Chapter 5, Manipulating cells

85

86

Programming e.Spreadsheet Reports

Chapter

6
Chapter 6

Manipulating cell data

Initiating in-cell editing using code


Use the startEdit method to begin edit mode for the active cell. You can start from a double-click event, a menu option, or some other place. Be sure to set the first parameter to false if you want to edit the existing data in the cell without clearing it out.

Syntax
public void startEdit(boolean clear, boolean inCellEditFocus, boolean arrowsExitEditMode)

Parameters
Parameter clear inCellEditFocus Description If set to true, the edit bar is cleared as edit mode commences. If set to true, the editing focus is given to in-cell editing. If set to false, editing focus is given to the edit bar. If set to true, edit mode is exited when an arrow key is pressed.

arrowsExitEditMode

Chapter 6, Manipulating cell data

87

Using the e.Spreadsheet Designer


1 Press the F2 key. 2 Enter data.

Code example
This code example allows in-cell editing without clearing the cell, gives the editing focus to in-cell editing, and exits edit mode when any arrow key is pressed.
jbook1.startEdit(false, true, true)

Data entry using code


Entering dates using code
The key to entering dates in a worksheet is to enter them as numeric data rather than as text. Dates are stored in Gregorian format in e.Spreadsheet, using a numerical value representing the number of days since January 1, 1900 (day 1). Dates entered as numerical values are formatted to display as a date (Example 1) or as a string in date format. Data entered in date format (Example 2) is automatically interpreted as a true date.

Using the e.Spreadsheet Designer


Example 1: Entering dates as numerical values and applying a date format. The number 27945 is July, 4, 1976. 1 Enter 27945 in a worksheet cell. 2 Choose FormatCells 3 Select the Number tab. 4 Select Date from the Categories list box. 5 Select a date format from the Number Format list box or create a new one in the text box. 6 Choose OK. Example 2:

88

Programming e.Spreadsheet Reports

Entering dates as date strings. 1 Enter 7/4/76 in a cell. 2 The autoformat feature automatically formats the entry as a date and stores it internally as a numerical value.

Code Example
The first two lines of this code example enter the date as a pure number and apply a format. The number 27945 is July 4, 1976. The third line enters the date as a date string.
jbook1.setNumber(27945); jbook1.setValueFormat("mm/dd/yy"); jbook1.setEntry("07/04/76");

Writing a formula that increments the date


Either using the e.Spreadsheet Designer or from code, use the MONTH function, increasing it incrementally by 1, as an argument to the DATE function to increment the date by months.

Using the e.Spreadsheet Designer


1 Type the starting date in cell A1.
=DATE(1999, 11, 1)

2 Type this formula in cell A2 to calculate the next month.


=DATE(YEAR(A1), MONTH(A1)+1, 1)

Code Example
Enter the starting date in cell A1. Enter the formula for the next month in cell A2.
jbook1.setFormula(0, 0, "DATE(1999, 11, 1)"); jbook1.setFormula(0, 1, "DATE(YEAR(A1), MONTH(A1)+1, 1)");

Entering one value in all cells in a selected range


To copy one value throughout a range, use the setEntry, setSelection, editCopyDown and editCopyRight methods as illustrated in the code example.

Chapter 6, Manipulating cell data

89

Using the e.Spreadsheet Designer


1 Add data to a cell. 2 Use the mouse to grab the selection handle box in the bottom right corner of the active cell marker. 3 Drag the active cell right or down. 4 When the mouse button is released, the data is copied.

Code Example
try { jbook1.setEntry(0, 0, "text to be copied"); jbook1.setSelection(0, 0, 10, 10); jbook1.editCopyDown(); jbook1.editCopyRight(); } catch (com.f1j.util.F1Exception err) { }

Loading data from an array


The code example below creates a two-dimensional array and populates it with data, then uses the copyDataFromArray method to copy the data into e.Spreadsheet. Using the copyDataFromArray method (which dumps raw data into a worksheet without formatting or updating cell information) is not the same as pasting data using the editPaste method.

Code Example
try { double[][] dataArray = new double[3][5]; for (int i=0; i<3; i++) { // Allocate an array for each row for (int j=0; j<5; j++) { dataArray[i][j] = i*j+100; } } jbook1.copyDataFromArray(0, 0, 0, 2, 4, dataArray); } catch (com.f1j.util.F1Exception err) { }

90

Programming e.Spreadsheet Reports

Importing large blocks of information


The methods listed in the table below can be used to move large blocks of information. The method to use depends on the type of data and where the data is moved from. Code examples are given for each method below. Method copyDataFromArray setClip setClipValues Description Moves data from an array. Transfers data from a String. Transfers data from a string, ignoring any formatting.

Code Examples
Example 1: This code example uses the copyDataFromArray method.
double[][] data = new double[10][10]; for (int i=0; i<data.length; i++) { for (int j=0; j<data.length; j++) { data[i][j]=(double)i*j; } } jbook1.copyDataFromArray(0, 0, 0, 9, 9, data);

Example 2: This code example uses the setClip method to write a tab-delimited text block to a worksheet.
String m_strTest = "This is a test of the setClip method \t 1/1/2000"; jbook1.setActiveCell(0, 0); jbook1.setClip(m_strTest);

Example 3: This code example uses the setClipValues method to write a tab-delimited text string to a worksheet, ignoring formatting.
String m_strTest = "This is a test of the setClipValues method \t 1/1/2000"; jbook1.setActiveCell(0, 0); jbook1.setClipValues(m_strTest);

Chapter 6, Manipulating cell data

91

Sorting
Using the sort and sort3 methods
To sort, use either the sort or sort3 method. The sort method takes one or more keys. The sort3 method always takes 3 keys. The sort3 method does the same thing as the sort methodits just used as a convenience when you only have 3 keys. When defining sort keys, specify the row or column number to serve as a key. Use a positive number to define an ascending key; use a negative number to define a descending key. If data is sorted by rows, each row of data in the range is considered a record and sorted together. If data is sorted by columns, each column in the specified range is considered a record and sorted together.

Syntax(sort)
public void sort(int row1, int col1, int row2, int col2, boolean sortByRows, int[] keys)

Parameters
Parameter row1 col1 row2 col2 sortByRows keys Description first row in range to be sorted. first column in range to be sorted. last row in range to be sorted last column in range to be sorted. Specifies how data is sorted. If set to true, data is sorted by rows; if set to false, data is sorted by columns. Identifies the key or keys to use to sort the data.

Syntax(sort3)
public void sort3(int row1, int col1, int row2, int col2,

92

Programming e.Spreadsheet Reports

boolean sortByRows, int key1, int key2, int key3)

Parameters
Parameter row1 col1 row2 col2 sortByRows Description first row in range to be sorted. first column in range to be sorted. last row in range to be sorted last column in range to be sorted. Specifies how data is sorted. If set to true, data is sorted by rows; if set to false, data is sorted by columns. Identifies the primary key used to sort the data. Identifies the secondary key used to sort the data. Pass 0 to ignore. Identifies the final key used to sort the data, relative to the starting column. Pass 0 to ingore.

key1 key2 key3

Code Examples
Example 1: This example illustrates how to sort using one or a variable number of keys:
int myarray[] = {1, 2}; try { jbook1.sort(1, 1, 10, 10, true, myarray); } catch (com.f1j.util.F1Exception err) { }

Example 2: This example illustrates how to sort using 3 or 4 keys, using column 2 of the selection as the primary key, column 1 as the secondary key, and column 3 as the third key.
try { jbook1.sort3(0, 0, 10, 2, true, 2, 1, 3); } catch (com.f1j.util.F1Exception err) { }

Chapter 6, Manipulating cell data

93

Sorting dates or numbers with formatting


The e.Spreadsheet program sorts both text and numbers. However, if numbers (or dates) are entered as text with the setText method, applying a sort will sort numbers textually rather than based on numerical value, ordinal date, etc. To ensure that numbers (and dates) are sorted correctly, enter them using the setEntry or setNumber methods.

Code Example
// To sort dates, use setEntry(). jbook1.setEntry("6/9/2000"); // To sort numbers use setNumber() or setEntry(). jbook1.setNumber(24); //or jbook1.setEntry("24");

Sorting data with blank cells in the sort range


Blank cells are placed at the end of a sort range. If you would like to sort a range of cells containing blank cells, and would like the blank cells to remain after the sort, copy the sort range and put it off the visible area of the worksheet. Apply the sort method to the temporary data range, loop through the sorted values, and place them back in the original range to the cells containing data.

Code Example
int myarray[] = {1}; try { // Select the data and move it to another place on the sheet jbook1.setSelection(0, 0, 10, 0); jbook1.editCopy(); jbook1.setSelection(0, 4, 10, 4); jbook1.editPaste(); // Sort this range jbook1.sort(0, 4, 10, 5, true, myarray); // Replace the data in the original range but only in non-empty cells int j = 0; for (int i = 0;i <= 10;i++) { if (jbook1.getType(i,0)! = 0) { jbook1.setText(i,0,jbook1.getText(j, 4));

94

Programming e.Spreadsheet Reports

j++; } } // Delete the temporary range of data jbook1.setSelection(0, 4, 10, 4); jbook1.clearRange(0, 4, 10, 5, jbook1.eClearAll); } catch (com.f1j.util.F1Exception err) { }

Concatenating text
To concatenate text, use the ampersand (&) symbol in the e.Spreadsheet Designer, or use the setFormula method from code.

Using the e.Spreadsheet Designer


Where cell: A1 A2 A3 A3 displays contains: Tom Smith ="Mr. "&A1&" "&A2 Mr. Tom Smith

Code Example
int m_iRow, m_iCol, m_iSheet; jbook1.setFormula(m_iSheet, m_iRow, m_iCol, "Mr. "&A1&" "&A2); jbook1.setFormula(m_iRow, m_iCol, "Mr. "&A1&" "&A2); jbook1.setFormula("Mr. "&A1&" "&A2);

Chapter 6, Manipulating cell data

95

Accessing cell content


Getting text value of a formula
The getFormula method returns the text value of a cells formula.

Code Examples
Example 1: This returns the text value for the currently selected cell.
try { String s = jbook1.getFormula(); } catch (com.f1j.util.F1Exception e1) { }

Example 2: This returns the text value for the cell reference given. The arguments (1, 1) are Row, Col.
try { String s = jbook1.getFormula(1, 1); } catch (com.f1j.util.F1Exception e1) { }

Example 3: This returns the text value for the cell reference given. The arguments (1, 1, 1) are Sheet, Row, Col.
try { String s = jbook1.getFormula(1, 1, 1); } catch (com.f1j.util.F1Exception e1) { }

Example 4: This example shows how to access the underlying spreadsheet model for server-side deployments. It returns the text value for the cell reference given. The arguments (1, 1) are Row and Col.
try { com.f1j.ss.Book book = new com.f1j.ss.BookImpl();

96

Programming e.Spreadsheet Reports

book.initBook(); book.getSheet(0).setFormula(1, 1, "sum(A1:B3)"); // Puts in formula String s = book.getSheet(0).getFormula(1, 1); } catch (com.f1j.util.F1Exception e1) { }

Finding out cell data type


You can use one of the getType methods to find out cell data type using code. The getType methods return one of the type constants listed below. Note that the getType method returns a negative value for the type constant if the cell contains a formula. Type Constant eTypeEmpty eTypeError eTypeLogical eTypeNumber eTypeText Cell data type Nothing in the cell Cell containing an error Cell containing a Boolean value: true or false. Cell containing a number value. Cell containing a text string.

Code Examples
Example 1: This code example returns the cell type of the active cell.
try { short sType = jbook1.getType(); } catch (com.f1j.util.F1Exception e1) { }

Example 2: This code example returns the cell type of the specified cell (row 1, column 1).
try { short sType = jbook1.getType(1, 1); } catch (com.f1j.util.F1Exception e1) { }

Example 3: This code example returns the cell type of the specified cell (sheet 0, row 1, column 1).

Chapter 6, Manipulating cell data

97

try { short sType = jbook1.getType(0, 1, 1); } catch (com.f1j.util.F1Exception e1) { }

Getting cell value prior to user editing


To get the value prior to user editing, call getEntry in the StartEditEvent object. This will return the previous value since the EndEditEvent object has not placed the value into the cell. Add the code in the code example to the StartEditEvent object.

Code Example
try { String strPrev = jbook1.getEntry(); } catch (com.f1j.util.F1Exception e1) { }

Determining defined name status and location


The code example below uses DefinedName to determine whether a specific defined name is in use and return its location.

Code Example
This code example checks to see if the defined name "Myname" exists. If the name doesnt exist, an exception is thrown.
try { String n = jbook1.getDefinedName("Myname"); } catch (com.f1j.util.F1Exception e1) { }

Returning string representations of cell location


Use the formatRCNr method to return a string representation of a cell.

Code Example
int iRow = 0, iCol = 0; boolean bolCellRefType = false; String strTest = jbook1.formatRCNr(iRow, iCol, bolCellRefType);

98

Programming e.Spreadsheet Reports

jbook1.messageBox(strTest, "", (short)3);

Chapter 6, Manipulating cell data

99

100

Programming e.Spreadsheet Reports

Chapter

7
Chapter 7

Referencing cells

Working with defined names


Creating or modifying a defined name
A defined name assigns a name to a cell, group of cells, value, or formula. A defined name cannot begin with combinations of letters and numbers that would correspond to worksheet column letters and row numbers (A through AVLH followed by 1 to 1,073,741,824: for example, VAL1 or S3548). The example code below sets the defined name to Work and places the named cell into the workbook.

Syntax
public void setDefinedName(java.lang.String name, java.lang.String formula, int row, int col)

Chapter 7, Referencing cells

101

Parameters
Parameter name Description A defined name. Enter an existing name if returning the formula associated with the name or changing the value associated with the name. Enter a unique name if creating a new value. Describes the range, value, or formula represented by the name parameter. A name can refer to a cell, a group of cells, a value, or a formula. When setting name, do not include a leading equal sign (=) in the formula. Relative row references are relative to this row. Relative column references are relative to this column.

formula

row col

Code Example
// Assigns the defined name Work to cell $D$4. jbook1.setDefinedName("Work", "Sheet1!$D$4", 0, 0); jbook1.setFormula(1, 1, "Work"); // Assigns the defined name Chance to the formula RAND()*100. jbook1.setDefinedName("Chance", "RAND() * 100"); jbook1.setFormula(3, 3, "Chance"); // Assigns the defined name Goal the text value Total Net Gain. jbook1.setDefinedName("Goal", "\"Total Net Gain\""); jbook1.setFormula(3, 3, "Goal");

Creating worksheet-specific defined names


To set a sheet level name, add Sheetn! at the beginning of the name when creating a defined name (e.g., Sheet1!mysheetname, or Sheet2!mysheetname). Sheet level names override workbook names for formulas on the same sheet. Sheet level names work the same as other defined names and may be referred to explicitly in formulas.

Using the e.Spreadsheet Designer


1 Choose InsertName. 2 Type Sheet1!mysheetname in the Name: text entry area. 3 Type a formula for the name in the Formula: text entry area . 4 Choose Add or OK.

102

Programming e.Spreadsheet Reports

Code Example
This code example sets the sheet level name mysheetname to cell $A$1.
jBook1.setDefinedName("Sheet1!mysheetname", "$A$1")

Determining the number of defined names in use


Though it appears that the defined name count never gets updated when deleting names, the deleted names are left in the table (and counted) until e.Spreadsheet does garbage collection. If the name is not referred to, it is removed when garbage collection is done. When looping through the names, check for a formula of "" to determine that the name is not defined. See the code example.

Code Example
if (jbook1.getDefinedName("Test1").compareTo("") == 0){ }

Referencing external cells


Use the setFormula method to reference a cell outside the current workbook using code. Whether you reference an external cell from the e.Spreadsheet Designer or from code, both workbooks must be loaded in the same e.Spreadsheet Designer window or group.

Using the e.Spreadsheet Designer


The syntax for the formula is [Workbook]Sheet!Range. Type and enter the following formula in a cell to reference A1 of Sheet1 of Workbook2, where Workbook2 is the name of the external workbook you are referencing.
=[Workbook2]Sheet1!$A$1

The current workbook and the workbook referred to must be in the same workbook Group. For more information, see Grouping workbooks in Chapter 8, Formatting worksheets.Grouping workbooks.

Chapter 7, Referencing cells

103

Code Example
This code sets the JBooks to be in the same Group, names the workbooks, then uses the setFormula method to reference the external cell A1 in sheet 1 of the workbook secondWB.
jbook1.setGroup("MyGroup"); jbook2.setGroup("MyGroup"); jbook1.setWorkbookName("firstWB"); jbook2.setWorkbookName("secondWB"); jbook1.setFormula(0, 0, "[secondWB]Sheet1!A1");

The e.Spreadsheet API also includes a setFormulaLocal method which should only be used as a method of preparing e.Spreadsheet to receive a formula entered by a user in the users local format as input. In most cases not involving user interaction, the setFormula method is preferred.

104

Programming e.Spreadsheet Reports

Part

3
Part 3

Formatting

Part 3, Formatting

105

106

Programming e.Spreadsheet Reports

Chapter

8
Chapter 8

Formatting worksheets

Chapter 8, Formatting worksheets

107

Manipulating worksheets
Adding a sheet to the end of the sheet list
The simplest way to specify the number of worksheets in a newly created workbook is to use the setNumSheets method. To add worksheets between existing worksheets, use insertSheets. To return the number of sheets in the current workbook, use getNumSheets. To delete worksheets, use deleteSheets.

Code Example
jbook1.setNumSheets(4);

Displaying a specific sheet


The setSheet method displays a specific sheet using sheet index numbers. Worksheets are indexed beginning at 0.

Using the e.Spreadsheet Designer


Choose the desired sheet tab.

Code Example
jbook1.setNumSheets(2); jbook1.setSheet(1);

Deleting the active sheet


Use the editDeleteSheets method. e.Spreadsheet prevents the deletion of the last sheet in a workbook.

Code Example
This code sets the sheet count to 2, makes the second sheet the active sheet, and deletes sheet2 (the active sheet).
jbook1.setNumSheets(2); jbook1.setSheet(1); jbook1.editDeleteSheets(); // Deletes sheet2(the active sheet)

108

Programming e.Spreadsheet Reports

Changing the look and feel


In e.Spreadsheet there are three look and feel options: Metal, CDE Motif, and Windows. These options can be selected by the user or using code. The default look and feel is Metal.

Using the e.Spreadsheet Designer


1 Choose ToolsPreferences. 2 Select the General tab. 3 Select Metal, CDE Motif, or Windows in the Look and Feel list box. 4 Choose OK.

Code Example
This example changes the Look and Feel of e.Spreadsheet:
// Changes the look and feel of the program javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows. WindowsLookAndFeel"); // Updates all of the components javax.swing.SwingUtilities.updateComponentTreeUI(JBook);

Changing the worksheet type


Using the setSheetType method in the com.f1j.ss.Sheet class, e.Spreasheet worksheets may be set to chart sheets or worksheet sheets. Chart sheets may also be added from the e.Spreadsheet Designer. Changing sheet type should only be done when a sheet is first created.

Using the e.Spreadsheet Designer


To add a chart sheet: 1 Add a chart to a worksheet. 2 Right-click on the chart to display the context menu. 3 Choose Location to display the Chart Location dialog. 4 Select Separate Sheet. 5 Type a name for the chart sheet. 6 Click OK.

Chapter 8, Formatting worksheets

109

Syntax
public void setSheetType(short sheetType)

Parameters
Parameter eSheetTypeSheet eSheetTypeChart Description a normal worksheet sheet a chart sheet

Code Example
This code sets the first sheet in the workbook to be a chart sheet.
jBook1.getSheet(0).setSheetType(com.f1j.ss.constants.eSheetTypeChart);

Hiding worksheets
The setHiddenState method sets worksheets to be shown, hidden, or very hidden. Worksheets may be set to hidden from code or from the e.Spreadsheet Designer. Hidden worksheets are prevented from initially displaying in the e.Spreadsheet GUI, but the e.Spreadsheet Designer can be used to display these sheets. Very hidden worksheets may only be displayed from code, are not accessible via, and never display in the GUI.

Using the e.Spreadsheet Designer


1 Create a workbook containing two or more worksheets. 2 Choose FormatSheetVisibilityto display the Visible Sheets dialog. 3 Deselect the sheet or sheets to hide. 4 Select the sheets to show. 5 Choose OK.

Syntax
public void setHiddenState(short hiddenState)

Parameters
Parameter hiddenState Description a flag indicating the sheet display status:

110

Programming e.Spreadsheet Reports

Parameter

Description Tag eSheetShown eSheetHidden eSheetVeryHidden Description display the sheet. hide the sheet and allow GUI display setting changes. hide the sheet and disallow GUI display setting changes.

Code Example
This code example sets the first sheet in the workbook to never display in the GUI.
book.getLock(); book.getSheet().setHiddenState(com.f1j.ss.Constants.eSheetVeryHidden); book.releaseLock():

Getting the name of the active worksheet


The getSheetName method returns the name of the worksheet specified by index number. Sheets are indexed beginning at 0. To get the name of the active sheet, use the getSheet method in place of the worksheet index number parameter. For information about how to name a worksheet, see Naming worksheets later in this chapter.Naming worksheets.

Code Example
This code returns the name of the active sheet.
String mySheet = jbook1.getSheetName(jbook1.getSheet());

Deselecting a worksheet using code


Pass false to the setSheetSelected method to deselect a worksheet. This method will not deselect a worksheet if it is the only sheet selected.

Code Example
The following code assumes that multiple sheets are selected and that the first sheet (sheet 0) in the workbook is one of the selected sheets.
jbook1.setSheetSelected(0, false); // Deselects the first sheet

Chapter 8, Formatting worksheets

111

Switching between worksheets with AllowSelections or ShowSelections set to false


Calling the setAllowSelections property with false or the setShowSelections property with eShowOff prevents switching between worksheets in a workbook. If you dont want to have selections shown but still want to navigate through the worksheets, hide the tabs on the workbook and use some other means of navigation such as using the setSheet method.

Removing the view window border


To remove the border, call the setBorder property with false. You can also check the border status using the isBorder method. The isBorder method returns true if theres a border, false if not.

Using the e.Spreadsheet Designer


1 Choose ToolsOptions. 2 Select the General tab. 3 Deselect Border. 4 Choose OK.

Syntax
public void setBorder(Boolean border) public boolean isBorder()

Code Example
jbook1.setBorder(false); // Sets the border to false

Exporting a worksheet with no gridlines to Excel


To save window-specific information (like whether to display gridlines) to an exported file, call the saveViewInfo method before writing the file.

Code Example
jbook1.setShowGridLines(false); jbook1.saveViewInfo(); jbook1.write(System.getProperty("user.dir") + java.io.File.separator +

112

Programming e.Spreadsheet Reports

"test.xls", new com.f1j.ss.WriteParams(jbook1.eFileExcel97));

Outlining
Worksheet outlining allows a user to expand or collapse sets of rows or columns on a worksheet to change the data viewed on the sheet (creating summary and variously-detailed views). A worksheet can have up to eight levels of grouped rows and columns outlined on a sheet. To set up outlining from code, use the setRowOutlineLevel and setColOutlineLevel methods to arrange rows and columns into detail groups. The setColSummaryBeforeDetail and setRowSummaryBeforeDetail methods set where summary rows and columns appear (before or after the row or column detail information). The setRowOutlineLevel and setColOutlineLevel methods establish the outline level by either setting it to a specific detail level (0-8) or incrementing it by adding one to the currnent outline level.

Using the e.Spreadsheet Designer


To create an outline on a worksheet: 1 Select the entire row(s) or column(s) that contains detail information. 2 Choose DataOutliningIncrease Detail Level. To move rows or columns to a higher detail bracket: 1 Select the row(s) or column(s) you want to remove from the bracket. 2 Choose DataOutliningDecrease Detail Level. To remove rows or columns from all detail brackets: 1 Select the row(s) or column(s) you want to remove from all brackets. 2 Choose DataOutliningClear Outlines.

Syntax
public void setColOutlineLevel(int col1, int col2, int outlineLevel, boolean additive)

Chapter 8, Formatting worksheets

113

Parameters
Parameter col1 col2 outlineLevel additive Description the first column in the range. the last column in the range. the level at which to set the outline. An integer from zero to seven Specifies whether the outline level is set to an absolute value or added to the current outlineLevel setting. If additive is set to False, the outline level is set to the current outlineLevel setting.

Syntax
public void setColOutlineCollapsed(int col, boolean collapsed)

Parameters
Parameter col Description The column to expand or collapse. The column must currently have an outline type of eOutlineCollapsed or eOutlineExpanded. Set to true to collapse the outline group; false to expand it.

collapsed

Syntax
public void setColSummaryBeforeDetail(boolean summaryBeforeDetail)

Parameters
Parameter summaryBeforeDetail Description If set to true, column outline summaries display before (to the left of) column detail information.

Syntax
public void setRowOutlineCollapsed(int row, boolean collapsed)

114

Programming e.Spreadsheet Reports

Parameters
Parameter row Description The row to expand or collapse. The row must currently have an outline type of eOutlineCollapsed or eOutlineExpanded. Set to true to collapse the outline group; False to expand it.

collapsed

Code Example
Example 1: This example adds outlining by increasing the detail level (creating groups) of sets of 11 rows leaving each 12th row to hold summary information. It also creates a secondary row outline level within the initial levels and a column outline level that includes columns B through D and sets the column outline summary to display before the detail columns.
public void doOutlining(JBook b) throws Exception { b.setRowOutlineLevel(0,10,1,false); //Group rows 1-11. Summary row = 12 b.setRowOutlineLevel(12,20,1,false); //Group rows 13-21. Summary row =22 b.setRowOutlineLevel(22,39,1,false); //Group rows 23-40. Summary row =41 b.setRowOutlineLevel(0,5,1,true); // Add secondary group from rows 1-6 b.setRowOutlineLevel(7,9,2,false); // Add secondary group from rows 8-10 // (a different way) b.setColOutlineLevel(1, 3, 1, false); // Group B..D b.setColSummaryBeforeDetail(true); // Put +/- in col 0 }

Example 2: This code example groups rows 0-5 and collapses them (hides them behind) the summary level. Row 6 holds the subtotal.
com.f1j.ss.Sheet s = b.getBook().getSheet(0); s.setRowOutlineCollapsed(6, true); // Rows 0-5 grouped with row 6 // holding the subtotal. The // setRow(Col)OutlineCollapsed // method operates on these // subtotal rows.

Working with Views

Chapter 8, Formatting worksheets

115

Giving e.Spreadsheet focus


Use the requestFocus method in each panels Focus event to give e.Spreadsheet the focus.

Code Example
jbook1.requestFocus(); // Gives jbook1 the focus

Showing only part of the sheet when using multiple views


After attaching multiple views, use the setMinCol, setMinRow, setMaxCol, and setMaxRow methods to limit the viewing area of each view. For information about attaching multiple views, see Grouping workbooks later in this chapter.Grouping workbooks.

Code Example
try { jb2.attach(jb1); jb2.setShowEditBar(false); jb2.setMinRow(0); jb2.setMaxRow(5); jb2.setMinCol(0); jb2.setMaxCol(6); } catch (com.f1j.util.F1Exception e) { } }

Changing view scale


The setViewScale method sets the current display scale for a workbook. Enter an integer between 10 and 400 to set the view scale to that percentage.

Using the e.Spreadsheet Designer


1 Choose ViewZoom. 2 Select the desired scale.

Code Example
jbook1.setViewScale(200); // Set the view scale to 200%

116

Programming e.Spreadsheet Reports

Setting default font


Use the setDefaultFont method to change the default font. The setDefaultFont method takes parameters for changing the name and size of the font. When setting the size, you can specify points by using a positive number or twips by using a negative number. When specifying twips, setDefaultFont uses the absolute value of the number you provide for size. The default font determines column widths when column widths are based on character widths.

Using the e.Spreadsheet Designer


1 Choose FormatDefault Font to open the Default Font dialog. 2 Select the desired font type and size in Font: and Size:. 3 Choose OK.

Code Examples
Example 1: This code example sets the default font to times, 12 point.
jbook1.setDefaultFont("Times", 12);

Example 2: This code example sets the default font to times, 240 twips.
jbook1.setDefaultFont("Times", -240);

Resizing columns as data changes


To resize columns as data changes, begin by implementing a StartEditListener and EndEditListener. Continue by defining the startEdit method (in the StartEditListener interface). This startEdit method is called whenever the user begins to edit the contents of a cell. Then, use the getActiveCell method to get the cell the cursor is currently in. Now that we can track where the user is currently editing, the next step is to define the endEdit method (in the EndEditListener interface) and the getRow and getCol methods to get the row and column of the cell after editing. Finally, set the setColWidthAuto method to set the column size to match the size of the largest entry.

Code Example
// Implement the com.f1j.swing.StartEditListener and // com.f1j.swing.EndEditListener interfaces and register the classes.

Chapter 8, Formatting worksheets

117

jbook1.addStartEditListener(this); jbook1.addEndEditListener(this);

// Add a StartEditListener // Add an EndEditListener

jbook1.removeStartEditListener(this); // Remove a StartEditListener jbook1.removeEndEditListener(this); // Remove an EndEditListener // Define the startEdit function in the StartEditListener interface as: public void startEdit(com.f1j.swing.StartEditEvent event) { try { cellRef = jbook1.getActiveCell(); // Get the cell being edited. } catch (com.f1j.util.F1Exception e) { } } // Define the endEdit function in the EndEditListener interface as: public void endEdit(com.f1j.swing.EndEditEvent event) { try { int r = cellRef.getRow(); // Get the row of the cell just typed in. int c = cellRef.getCol(); // Get the column of the cell just typed in. jbook1.setText(r, c, event.getEditString()); // Set the text in that cell (because the text isnt actually set until // AFTER the EndEdit event is over) jbook1.setColWidthAuto(0, c, jbook1.getLastRow(), c, true); // Autofit the column (from row 0 to the last row) to be the size of the // largest entry } catch (com.f1j.util.F1Exception e) { } }

118

Programming e.Spreadsheet Reports

Grouping workbooks
Use the setGroup method to group workbooks to allow workbooks to reference cells in other workbooks. There are advantages and disadvantages to attaching multiple workbooks in the same group: Put multiple workbooks in the same group if you want to:
s s s

enable external cell references between workbooks. enable the attach(String workbookName) method. enable the WORKBOOKNAME applet parameter to attach multiple applets to the same workbook. ensure that all background processing is done on a single thread. save resources (memory) by having multiple workbooks share resources. lack of concurrency when manipulating multiple workbooks. Public methods must acquire a lock for all workbooks in the group before proceeding. allowing this workbook or other resources associated with it to be automatically garbage collected. If the workbook is part of a named group, it is referenced by a static collection of groups. This static reference makes it impossible for the Java Virtual Machine to garbage collect this view and workbook. This can be overcome by calling the destroy method when the workbook is no longer needed. each group having its own thread for background processing as well as certain other resources used primarily for workbook formulas.

s s

Dont put multiple workbooks in the same group if youre concerned about:
s

Syntax
public void setGroup(java.lang.String group)

Parameters
Parameter group Description the new group name for the workbook attached to this view. A value of null or "" will put the workbook in its own group.

Code Example
try {

Chapter 8, Formatting worksheets

119

jbook1.setGroup("Same"); jbook2.setGroup("Same"); jbook1.attach("workBook2"); // To attach using workbook name, both // JBooks must be in the same group. } catch (com.f1j.util.F1Exception err) { }

120

Programming e.Spreadsheet Reports

Working with worksheet tabs


Moving or removing worksheet tabs
Use the setShowTabs method to set the display status and position of the sheet name tabs on a workbook.

Syntax
public void setShowTabs(short showTabs)

Parameters
Parameter eTabsOff eTabsBottom eTabsTop Controls hide tabs tabs on bottom tabs on top

Using the e.Spreadsheet Designer


1 Choose ToolsOptions. 2 Select the General tab. 3 Choose Off, Bottom, or Top from the Sheet Tabs list. 4 Choose Apply or OK.

Code Example
This code example sets the tabs to show at the top of the workbook.
jbook1.setShowTabs(JBook.eTabsTop);

Preventing tabs from reappearing at runtime


Calling initWorkbook at run-time resets any options set at design-time back to the defaults. The default for the tabs is to have tabs on.

Chapter 8, Formatting worksheets

121

Moving through worksheets in a workbook


The setSheet method sets the focus to the selected sheet number using the sheet index number. Sheets are indexed from left to right starting at 0.

Code Example
This code sets the number of sheets in the workbook to 2 and sets the active sheet to the 2nd sheet.
jbook1.setNumSheets(2); jbook1.setShowTabs(JBook.eShowOff); jbook1.setSheet(1);

Naming worksheets
The setSheetName method assigns a name to the specified worksheet. This name appears on the sheet tab. When you change a sheet name, formulas that reference the worksheet automatically update to reference the new sheet name.

Syntax
public void setSheetName(int sheet, java.lang.String sheetName)

Parameters
Parameter sheet sheetName Description The index number of the sheet. Worksheets are indexed from left to right beginning with 0. The name you want to give the sheet.

Using the e.Spreadsheet Designer


1 Double-click on a worksheet tab to open the Sheet Name dialog. 2 Type the desired sheet name in Sheet Name: text area. 3 Choose OK.

Code Example
This example sets the name of the first sheet in the workbook to Bob.
jbook1.setSheetName(0, "Bob");

122

Programming e.Spreadsheet Reports

Working with headers


Getting and setting row and column header dimensions
You can set and get row header width and column height using code with the getHeaderWidth, getHeaderHeight, setHeaderWidth, and setHeaderHeight methods. The getHeaderWidth and setHeaderWidth methods get or set the row header width in units equal to 1/256th of an average characters width in the default font. However, they get or set the column header height in twips. A twip is 1/ 1440 of an inch.

Using the e.Spreadsheet Designer


1 Select the top left header cell to select the entire sheet. 2 With the entire sheet selected, select a border in any header cell and drag it to the desired size. All cells in the workbook change to the new size.

Code Example
This code example doubles the current header height and width.
try { jbook1.setHeaderWidth(jbook1.getHeaderWidth()*2); jbook1.setHeaderHeight(jbook1.getHeaderHeight()*2); } catch (com.f1j.util.F1Exception err) { }

Getting and setting header text


Retrieve header text column headers using the getColText method and from row headers using the getRowText method. Set column and row header text using the setColText, setRowText, and setTopLeftText methods. Use: setColText, getColText to: Set/get the column header text

Chapter 8, Formatting worksheets

123

Use: setRowText, getRowText setTopLeftText, getTopLeftText

to: Set/get the row header text Set/get the top left header corner text

Using the e.Spreadsheet Designer


1 Double click on the header to bring up the Header Text dialog. 2 Type the desired text. 3 Choose OK.

Code Example
try { // Adds text to the first row and column headers jbook1.setColText(0, "Column Name"); jbook1.setRowText(0, "Row Name"); // Sizes the column to display the text jbook1.setColWidthAuto(0, 0, jbook1.getMaxRow(), jbook1.getMaxCol(), false); // Sizes the row header to be the same width as the column jbook1.setHeaderWidth(jbook1.getColWidth(0)); } catch (com.f1j.util.F1Exception err) { }

Setting header font


To format headers from code, select the headers by passing true for all of the parameters of the setHeaderSelection method, then applying the desired formatting using CellFormat and the formatting methods (setFontBold, setFontItalic, etc.).

Using the e.Spreadsheet Designer


1 Ctrl+Shift+Click on the header. 2 With the header selected, choose FormatCells. 3 Change the formatting as desired.

Syntax
public void setHeaderSelection(boolean topLeftHeader, boolean rowHeader,

124

Programming e.Spreadsheet Reports

boolean colHeader)

Parameters
Parameter topLeftHeader rowHeader colHeader Description Specifies whether the cell at the intersection of the row and column headings is selected. Specifies whether the row headers are selected. Specifies whether the column headers are selected.

Code Example
try { // Set the selection to the headers jbook1.setHeaderSelection(true, true, true); com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); // Apply formatting just like to any other cell CellFormat1.setHorizontalAlignment(com.f1j.ss.CellFormat. eHorizontalAlignmentLeft); CellFormat1.setFontBold(false); CellFormat1.setFontItalic(true); CellFormat1.setFontSize(220); CellFormat1.setFontName("Arial"); jbook1.setCellFormat(CellFormat1); } catch (com.f1j.util.F1Exception err) { }

Turning row and column headers off


Use the setShowRowHeading and setShowColHeading methods to turn row and column headings off and on.

Using the e.Spreadsheet Designer


1 Choose FormatSheetProperties. 2 Choose the View tab. 3 Deselect the Row Heading and Column Heading checkboxes. 4 Choose OK.

Chapter 8, Formatting worksheets

125

Code Example
jbook1.setShowRowHeading(false); jbook1.setShowColHeading(false);

Resetting to default row and column header text


To reset headers, set them to null. Deleting and inserting a range of columns also resets the headers.

Using The e.Spreadsheet Designer


1 Double-click on the header. 2 Select and delete all text. The header text automatically changes back to the default.

Code Example
This code resets the first row and first column headers.
try { jbook1.setColText(0, null); jbook1.setRowText(0, null); } catch (com.f1j.util.F1Exception err) { }

Entering multiple-line column and row headers


From code, enter multiple-line text in a column or row header using the new line character, \n, to designate the beginning of a each new line.

Using the e.Spreadsheet Designer


1 Double click the header. 2 Type in a text string. 3 Press Enter to move to the next line.

Code Example
try { jbook1.setColText(0, "This is a \n new line"); jbook1.setHeaderHeight(jbook1.getHeaderHeight()*2); } catch (com.f1j.util.F1Exception err) { }

126

Programming e.Spreadsheet Reports

Working with columns and rows


Hiding or showing a column or row
Use the setColHidden or setRowHidden methods to hide rows or columns. Entering a column or row location and a Boolean hides or shows the specified column or row. Entering a range of columns/rows and a Boolean hides or shows the specified columns/rows. Alternatively, you could pass 0 to the setColWidth or setRowHeight method. If you want to keep users from changing the width or height, pass true to the setEnableProtection method. The Column Width and Row Height dialogs used in the e.Spreadsheet Designer can also be invoked using code with the ColWidthDlg or RowHeightDlg classes.

Using the e.Spreadsheet Designer


1 Choose FormatRow or FormatColumn. 2 Select Hide to hide the row or column. 3 Select Unhide to show the row or column.

Code Example
try { // Hides the first row and column jbook1.setColHidden(0, 0, true); jbook1.setRowHidden(0, 0, true); } catch (com.f1j.util.F1Exception err) { }

Maintaining column widths when importing data


To maintain column width when importing data, pass false to the setAdjustColWidth method. The column width is not changed when the data comes in from the database.

Chapter 8, Formatting worksheets

127

Code Example
com.f1j.data.DataRange range = book.getSheet(0).getDataRangeCollection().factory("test", 0, 0); range.setAdjustColWidth(false);

Identifying and counting visible rows in a worksheet


Use the getTopRow and getLeftCol methods, then loop through the cells checking the RangeToTwips API calls shown parameter and keep a running count. Here, the rangeToTwips method returns a shown, partially shown, or not shown parameter for each row.

Code Example
java.awt.Rectangle rect = new java.awt.Rectangle(); short shown; int shownCount = 0; try { int i = jbook1.getTopRow(); int j = jbook1.getLeftCol(); shown = jbook1.rangeToTwips(i, j, i+1, j+1, rect); while (shown!=0) { while (shown!=0) { shown = jbook1.rangeToTwips(i, j, i, j, rect); jbook1.setNumber(i, j, shown); j++; if (shown==1) shownCount = shownCount+1; } j = jbook1.getLeftCol(); shown = jbook1.rangeToTwips(i, j, i+1, j+1, rect); i++; } System.out.println(shownCount); } catch (com.f1j.util.F1Exception err) { }

Freezing rows and columns


Freezing rows and columns in a worksheet causes the designated columns and rows to always remain visible. These frozen rows or columns, called

128

Programming e.Spreadsheet Reports

panes, cannot be edited after freezing. If a user tries to select a cell in a frozen row or column, the entire row or column is selected, just as if a row or column heading were selected. To fix and unfix rows and columns, use the setFixedCols and setFixedRows methods. Setting the parameter for the starting row or column to 0 and the parameter for the number of fixed rows or columns to 1 freezes the first row or column. If a column or row is fixed and there are unfixed columns or rows to the left or above the fixed columns or rows, then those columns and rows will no longer be accessible. e.Spreadsheet will not scroll to the left of fixed columns or above fixed rows.

Using the e.Spreadsheet Designer


1 Select any cell. 2 Choose FormatFreeze Panes. 3 Rows and columns above and to the left of the selected cell are fixed.

Code Example
try { // Fixes the first two rows and columns jbook1.setFixedCols(0, 2); jbook1.setFixedRows(0, 2); } catch (com.f1j.util.F1Exception err) { }

Changing default column width


The setColWidthAuto method increases column width to fit the largest word and decreases column width down to the default width. To change the default width for a single column, use setColWidth(int, int). Use setColWidth(int, int, int, boolean) for multiple columns.

Using the e.Spreadsheet Designer


Select the column header of the column to be sized. 1 Choose FormatColumnAutofit Selection.

Syntax
public void setColWidth(int col, int width)

Chapter 8, Formatting worksheets

129

Column width can be specified in units equal to 1/256th of the character 0s width in the default font. You can also set column width in twips using one of the setColWidthTwips methods. Or

Syntax
public void setColWidth(int col1, int col2, int width, boolean defColWidth)

Parameters
Parameter Single Column Method: col width Multiple Column Method: col1 col2 width defColWidth number identifying the beginning column number identifying the ending column the column width Set to true for specified column width to become default, false if not. identifies a column by number the width of the column Controls

Code Example
This code example sizes the column to fit the text, even if it is smaller than the default column width.
try { jbook1.setColWidthAuto(0, 0, jbook1.getMaxRow(), jbook1.getMaxCol(), false); } catch (com.f1j.util.F1Exception err) { }

Getting column width in twips


Call the setColWidthUnits method with eColWidthUnitsTwips to set the column width units to twips. A twip is one TWentIeth of a printers Point, so there are 1,440 twips per inch.

130

Programming e.Spreadsheet Reports

To change back to the default unit, call the setColWidthUnits method with eColWidthUnitsNormal. The default column width unit is a unit equal to 1/ 256th of the character 0s width in the default font.

Code Example
This code example sets the column width units to twips.
jbook1.setColWidthUnits(jbook1.eColWidthUnitsTwips);

Setting the first row or column displayed


Use the setLeftCol and setTopRow methods to set the first row and column displayed.

Code Example
This code example sets column E and row 6 as the first column and row to display.
jbook1.setLeftCol(4); jbook1.setTopRow(5);

Scrolling
Scrolling through a worksheet using code
You can use the setLeftCol and setTopRow methods to cause the sheet to scroll left to right or top to bottom. To cause the sheet to scroll right, repeatedly call the setLeftCol method, increasing the value with each call. To cause the sheet to scroll down, Repeatedly call the setTopRow method, increasing the value with each call.

Code Example
Each time this code is run, it will scroll the sheet down one row and over one column.
try { int i = jbook1.getTopRow(); jbook1.setTopRow(i+1); int j = jbook1.getLeftCol();

Chapter 8, Formatting worksheets

131

jbook1.setLeftCol(j+1); } catch (com.f1j.util.F1Exception err) { }

Leaving the scroll bar on


To keep the scroll bar on continuously, call the setShowVScrollBar and setShowHScrollBar methods with eShowOn.

Code Example
jbook1.setShowVScrollBar(jbook1.eShowOn); jbook1.setShowHScrollBar(jbook1.eShowOn);

132

Programming e.Spreadsheet Reports

Chapter

9
Chapter 9

Formatting cells

This chapter contains the following topics:


s s s s s

Formatting a cell or range Formatting cells Formatting cell contents Hyperlinking from worksheet cells Using conditional formatting

Chapter 9, Formatting cells

133

Formatting a cell or range


To format a cell or range, you first create a cell format object, then apply the desired combination of formatting methods as demonstrated in the code example below.

Code Example
com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setFontItalic(true); CellFormat1.setFontBold(true); CellFormat1.setFontColor(java.awt.Color.magenta.getRGB()); // Formats a range jbook1.setCellFormat(CellFormat1, 0, 0, 5, 5); jbook1.setText(0, 0, "test");

Formatting cells
Setting cell background color
Generally, to set the background color of a cell, use the same code as that used for setting the cell pattern (below). To make a cell a solid color, use setPattern and setPatternBG and choose pattern 1.

Code Example
jbook1.setSelection(0, 0, 0, 0); com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setPattern(CellFormat1.ePatternSolid); CellFormat1.setPatterFG(java.awt.Color.lightGray.getRGB()); // Format the currently selected cell. jbook1.setCellFormat(CellFormat1);

134

Programming e.Spreadsheet Reports

Do not confuse a cells foreground color with the text color or the background color with the color of the cell. Foreground color, text color, background color and cell color are all different things. The foreground color applies to patterns and is only displayed when a pattern is applied to the cell. The foreground color is the color of the lines of the pattern; the background is the color that shows through between the lines. The text color is set separately using the setFontColor method.

Setting patterns for cells


To set the pattern for a cell or range, select a cell or range of cells using the setSelection method and apply a pattern using the setCellFormat method. Alternatively you can set the pattern of a cell format object, then specify the range using the setFormat method. The code examples below demonstrate both methods. In order for a pattern to show, make sure to set a foreground or background color.

Using the e.Spreadsheet Designer


1 Select the range to which to apply the pattern. 2 Choose FormatCells. 3 Select the Fill tab. 4 Select the color or pattern to apply. 5 Choose Apply or OK.

Code Examples
Example 1: This code example uses the setSelection and setCellFormat methods to apply a solid light gray pattern to cell A1.
jbook1.setSelection(0, 0, 0, 0); com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setPattern(CellFormat1.ePatternSolid); CellFormat1.setPatternFG(java.awt.Color.lightGray.getRGB()); // Applies formatting jbook1.setCellFormat(CellFormat1);

Example 2:

Chapter 9, Formatting cells

135

This code example uses font formatting methods and the setCellFormat method to apply bold, italic magenta font formatting to the range A1:C3.
com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setFontItalic(true); CellFormat1.setFontBold(true); CellFormat1.setFontColor(java.awt.Color.magenta.getRGB()); // Applies formatting jbook1.setCellFormat(CellFormat1, 0, 2, 0, 2);

Pattern Constants Shading Patterns ePattern10Percent ePattern25Percent ePattern40Percent ePattern5Percent ePattern70Percent ePattern80Percent ePatternNull Line Patterns ePatternDarkHorizontal ePatternNarrowHorizontal ePatternDarkVertical ePatternNarrowVertical ePatternDarkDownwardDiagonal ePatternDashedDownwardDiagonal ePatternLightDownwardDiagonal ePatternWideDownwardDiagonal ePatternDashedHorizontal ePatternLightHorizontal ePatternDashedVertical ePatternLightVertical ePatternDarkUpwardDiagonal ePatternDashedUpwardDiagonal ePatternLightUpwardDiagonal ePatternWideUpwardDiagonal ePattern20Percent ePattern30Percent ePattern50Percent ePattern60Percent ePattern75Percent ePattern90Percent ePatternSolid

136

Programming e.Spreadsheet Reports

Pattern Constants (continued) ePatternDottedGrid ePatternSmallGrid Miscellaneous Patterns ePatternDottedDiamond ePatternLargeCheckerBoard ePatternPlaid ePatternSmallCheckerBoard ePatternSphere ePatternWave ePatternDiagonalBrick ePatternName ePatternHorizontalBrick ePatternOutlinedDiamond ePatternShingle ePatternSmallConfetti ePatternTrellis ePatternZigZag ePatternLargeGrid

Merging cells
Any contiguous range of cells that forms a rectangle can be merged. When e.Spreadsheet merges cells it removes cell borders within the range and deletes all data except the data in the top left cell. Merged cells function as a single cell on the worksheet, with the row/column reference from the cell in the top-left corner of the merged range. For example, merging cells A1:B5 results in a single cell with the cell reference A1. Adjacent cell references do not change after merging. To merge cells from code, first create a range using the setSelection method, then call the setMergeCells method with true to merge the cells.

Using the e.Spreadsheet Designer


To merge cells: 1 Select the range to merge. 2 Choose Merge Cells on the Formatting toolbar. To un-merge cells: 1 Select the merged cell. 2 Choose Merge Cells on the Formatting toolbar.

Chapter 9, Formatting cells

137

You can also merge or un-merge selected cells by toggling the Merge Cells checkbox on the Alignment tab of the Format Cells dialog.

Code Example
This code example creates a format object (cf) that sets the font color to black and merges the selected range, then merges ranges of cells using the setSelection and setCellFormat methods.
public void doMergedCells(JBook b) throws Exception { com.f1j.ss.CellFormat cf = b.getCellFormat(0, 3, 0, 3); cf.setFontColor(0x0000ff); cf.setMergeCells(true); b.setSelection(0, 3, 0, 4); b.setCellFormat(cf); // Merges range D1:E1 (horizontal) b.setSelection(1, 3, 2, 4); b.setCellFormat(cf); // Merges range D2:E3 (horizontal & vertical) cf.setOrientation((short)-45); // Only displays rotated under JDK 1.2+ b.setSelection(3, 3, 6, 3); // Merges D4:E7 (vertical) and rotates text. b.setCellFormat(cf); }

Displaying multiple-line data in one cell


To display multi-line data, use the new line constant \n to separate lines of text in the cell or turn on Wrap Text using the setWordWrap method.

Using the e.Spreadsheet Designer


1 Press F2 twice to open the Cell Text dialog box. 2 Use the enter key to insert a carriage return at the end of the text to enable multi-line text. Or 1 Choose FormatCells. 2 Select the Alignment tab. 3 Select Wrap Text. 4 Choose OK.

138

Programming e.Spreadsheet Reports

Code Example
// Using the new line "\n" constant. String strTest = "test" + "\n" + "New line"; jbook1.setText(1, 1, strTest); // Using the setWordWrap method. String strTest = "This is a test of word wrap"; com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setWordWrap(true); // Format a range. jbook1.setCellFormat(CellFormat1, 0, 0, 5, 5); // Test to see if formatting was applied. jbook1.setText(0, 0, strTest);

Turning cell protection on


The setEnableProtection method turns cell protection on and off for the entire worksheet. The default is off. Cells have to be locked or hidden and the setEnableProtection method called with true before the cells are locked or hidden.

Code example
com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setEnableProtection(true); //Format a range jbook1.setCellFormat(CellFormat1, 0, 0, 0, 0);

Turning type markers on


Use the setShowTypeMarkers method to turn type markers on or off. By default, type markers, the colored cell indicator frames, are not set.

Syntax
public void setShowTypeMarkers(boolean)

Chapter 9, Formatting cells

139

Parameters
Parameters true false Type Marker Default Settings Empty cell Blank formatted cell Value cell (number or text) Formula cell None Blue frame Green frame Red frame Description display markers hide markers

Code Example
jbook1.setShowTypeMarkers(true);

Formatting cell contents


Using vertical and horizontal alignment constants
Use the setHorizontalAlignment and setVerticalAlignment methods to set vertical and horizontal alignment. These methods require that you use a CellFormat object. For information about using a CellFormat object, see Formatting a cell or range earlier in this chapter.Formatting a cell or range.

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Alignment tab. 3 Choose from the selections in the Horizontal and Vertical list boxes in the Options frame. 4 Choose okay

Syntax
public void setVerticalAlignment(short alignment)

140

Programming e.Spreadsheet Reports

Parameters
Horizontal Constants eHorizontalAlignmentGeneral eHorizontalAlignmentLeft eHorizontalAlignmentCenter eHorizontalAlignmentRight eHorizontalAlignmentFill Effect Justifies data based on data type. Aligns data to the left of the cell. Centers data in the cell left to right. Aligns data to the right of the cell. Fills the cells with text entered in that cell. Justifies data. Centers the data across the selected range. Effect Aligns the data at the top of the cell. Centers the data top to bottom. Aligns the data at the bottom of the cell. Integer 0 1 2 3 4

eHorizontalAlignmentJustify eHorizontalAlignmentCenterAcrossCells

5 6

Vertical Constants eVerticalAlignmentTop eVerticalAlignmentCenter eVerticalAlignmentBottom

Integer 0 1 2

Code Example
This example will format the alignment to be right and top. The first line gets the cell format; the last sets the cell format. The middle lines set the horizontal and vertical alignment.
cellformat = jbook1.getCellFormat(); cellformat.setHorizontalAlignment(com.f1j.ss.CellFormat .eHorizontalAlignmentRight); cellformat.setVerticalAlignment(com.f1j.ss.CellFormat .eVerticalAlignmentTop); jbook1.setCellFormat(cellformat);

Chapter 9, Formatting cells

141

Applying different formatting to parts of a cell


Formatting may be applied to only a portion of a cell in e.Spreadsheet via the GUI or from code.

Code Example
This code example creates an array of cell format objects (cf) that sets cell text to bold, italic, underlined, and 14 pt. After setting the active cell to cell A4, the code applies each format separately, in order (0-3) to each successive word (string of characters between two spaces) of the data in the cell.
public void doMultiFontText(JBook b) throws Exception { com.f1j.ss.CellFormat cf[] = new com.f1j.ss.CellFormat[5]; for (int i = 0;i<cf.length;i++) cf[i] = b.getCellFormat(); cf[0].setFontBold(true); cf[1].setFontItalic(true); cf[2].setFontUnderline(true); cf[3].setFontSize(14 * 20); b.setActiveCell(0,5); String text = b.getText(0,5); int start = 0, stop = 0; for (int i = 0;i<cf.length;i++) { stop=text.indexOf(" ", start); b.setTextSelection(start, stop); b.setCellFormat(cf[i]); start = stop+1; }

Showing formula text or returned value


Call the setShowFormulas method with true to show the text of the formula; call it with false to show the value returned by the formula.

Using the e.Spreadsheet Designer


1 Choose FormatSheetProperties. 2 Select the View tab. 3 Choose Formulas to display the text of the formula. 4 Deselect Formulas to show the value returned by the formula.

142

Programming e.Spreadsheet Reports

5 Choose OK.

Code Example
jbook1.setShowFormulas(true); // To show formulas jbook1.setShowFormulas(false); // To show values

Hiding cell value


To hide a cells value, call the setHidden method with a parameter of true.

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Protection tab. 3 Choose Hidden in the Options frame. 4 Turn protection on by choosing FormatSheetEnable Protection.

Syntax
public void setHidden(boolean hidden)

Code Example
com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setHidden(true); // Format a range jbook1.setCellFormat(CellFormat1, 0, 0, 0, 0); // Test to see if formatting was applied jbook1.setText(0, 0, "test");

Hyperlinking from worksheet cells


e.Spreadsheet supports hyperlinking on Windows platforms. Hyperlinks may be added to a cell or range of cells using the e.Spreadsheet Designer or from code. Hyperlinks support includes links to:
s s

ranges within the same workbook, URLs (launches a browser),

Chapter 9, Formatting cells

143

s s

files, and e-mail. other ranges in the same worksheet other ranges in a different sheet in the same workbook, external files (any registered file type). Web pages e-mail addresses

Use the addHyperlink method to link worksheet cells to:


s s s s s

Syntax
addHyperlink(int iSheet, int iRow1, int iCol1, int iRow2, int iCol2, java.lang.String strLink, int iType, java.lang.String strToolTip)

Parameters:
Parameter iSheet iRow1 iCol1 iRow2 iCol2 strLink iType Description The sheet containing the range to add the hyperlink to. The beginning row coordinate of the range. The beginning column coordinate of the range. The ending row coordinate of the range. The ending column coordinate of the range. The link string. A URL, worksheet cell reference, or file address. An integer indicating the link type:

144

Programming e.Spreadsheet Reports

Parameter kRange kURLAbs kURLRel kFileAbs kFileRel kNet strToolTip

Description (continued) Integer 0 1 2 3 4 5 Range in a workbook Absolute URL Relative URL Absolute file path Relative file path Network file path

Valid link type constants:

The tooltip string. The default tooltip is used when this is null.

Code Examples
Example 1: This example creates a link to cell A100 in the same workbook.
jbook1.addHyperlink(0, 0, 0, 0, 0, "a100", com.f1j.ss.Hyperlink.kRange, "Link to cell a100");

Example 2: This example creates a link to an external workbook:


jbook1.addHyperlink(0, 0, 0, 0, 0, "[D:\example\example.vts]Sheet1!A1", com.f1j.ss.Hyperlink.kFileAbs, null);

Example 3: This example creates a hyperlink to an absolute URL.


jbook1.addHyperlink(0, 0, 0, 0, 0, "http://www.actuate.com", com.f1j.ss.Hyperlink.kURLAbs, "Actuate Website");

Example 4: This example creates a hyperlink to a relative URL.


jbook1.setHyperlinkBase("http://www.actuate.com/"); jbook1.addHyperlink(0, 0, 0, 0, 0, "sitemap.asp", com.f1j.ss.Hyperlink.kURLRel, null);

Example 5: This example passes through a hyperlink to a Microsoft Office bookmark. e.Spreadsheet reads and writes files that contain Office bookmarks, but does not use them within VTS files.
jbook1.addHyperlink(0, 0, 0, 0, 0, "D:\\excelworkbook.xls#Sheet2!A100", com.f1j.ss.Hyperlink.kFileAbs, null);

Chapter 9, Formatting cells

145

Example 6: This example creates a hyperlink to a file using a relative file path.
jbook1.addHyperlink(0, 0, 0, 0, 0, "\\test\\ExternalTestHyperlink.xls", com.f1j.ss.Hyperlink.kFileRel, null);

Example 7: This example creates a hyperlink to a different file type.


jbook1.addHyperlink(0, 0, 0, 0, 0, "C:\\temp\\Readme.pdf", com.f1j.ss.Hpyerlink.kFileAbs, null);

Example 8: Mail is supported by all commands in the mailto: protocol. This example creates a hyperlink that sends using to:, a cc: and a subject line.
jbook1.addHyperlink(0, 0, 0, 0, 0, "mailto:person@actuate.com?cc = somebody2@actuate.com&subject = Hyperlink Test", com.f1j.ss.Hyperlink.kURLAbs, null);

Using conditional formatting


Conditional cell formats are formats applied to a cell only when the value of a cell or formula meets a predetermined set of conditions. Users may set up to 3 conditions per cell. Conditional formats may include font colors and styles, and cell border colors, fill colors, styles, and patterns. From code, use methods from the ConditionalFormat class to set and apply conditional formatting.

Using the e.Spreadsheet Designer


To apply conditional formatting: 1 Select the range to which to apply the conditional formatting. 2 Choose FormatConditional to open the Conditional Format dialog. 3 Select the Conditions tab. 4 Select Add. 5 Select Cell Value to base the condition on the value of the cell contents or Formula to base it on a Formula. Formula criteria only works with formulas that return a boolean value (true or false). 6 Select the Font, Border, and Fill tabs and apply formatting desired for cells that meet the criteria.

146

Programming e.Spreadsheet Reports

7 Choose Apply or OK.

Syntax
public void setFormula1(java.lang.String formula1, int row, int col)

Parameters
Parameter formula1 row col Description The first formula for this conditional format. The row the formula will be relative to. The column the formula will be relative to.

Syntax
public void setFormula2(java.lang.String formula2, int row, int col)

Parameters
Parameter formula2 row col Description The second formula for this conditional format. The row the formula will be relative to. The column the formula will be relative to.

Syntax
public void setOperator(short operator)

Parameters
Parameter operator Description the operator for this conditional format

Chapter 9, Formatting cells

147

Parameter

Description eOperatorNone eOperatorBetween eOperatorNotBetween eOperatorEqual eOperatorNotEqual eOperatorGreaterThan eOperatorLessThan eOperatorGreaterThanOrEqual eOperatorLessThanOrEqual No comparison. Between two values. Not between two values. Equal to a value. Not equal to a value. Greater than a value. Less than a value. Greater than or equal to a value. Less than or equal to a value.

Syntax
public void setType(short type)

Parameters
Parameter type Description The type of conditional formatting to apply: eTypeNone eTypeCell eTypeFormula No conditional formatting. Formatting applied based on value in cell. Formatting applied based on boolean outcome of formula. true = apply formatting.

Syntax
public void setConditionalFormats(ConditionalFormat[] conditionalFormats)

Parameters
Parameter conditionalFormats Description an array of zero to three ConditionalFormat objects to apply to the current selection. If this is null, or has a length of zero, conditional formats are removed.

148

Programming e.Spreadsheet Reports

Code Example
This code example sets up an array of three conditional formats (condfmt [02]) and applies them using the setConditionalFormats method. The first two conditions use the setType and setFormula1 methods to set up a formulabased condition. The third condition sets up a value-based condition using the setOperator and setType methods.
public void doConditionalFormats(JBook b) throws Exception { com.f1j.ss.ConditionalFormat condfmt[] = new com.f1j.ss.ConditionalFormat[3]; condfmt[0]=new com.f1j.ss.ConditionalFormat(b.getBook()); condfmt[1]=new com.f1j.ss.ConditionalFormat(b.getBook()); condfmt[2]=new com.f1j.ss.ConditionalFormat(b.getBook()); // Condition #1 com.f1j.ss.CellFormat cf=condfmt[0].getCellFormat(); condfmt[0].setType(com.f1j.ss.ConditionalFormat.eTypeFormula); // Relative to row 1, columns are specified as absolute so column relative // value doesnt matter condfmt[0].setFormula1("and(iseven(row()), $C1 > 5000)", 0, 0); cf.setFontColor(0x00ff00); cf.setPattern(cf.ePatternSolid); cf.setPatternFG(0x999999); // Ensures this color gets selected b.setPaletteEntry(28, new Color(0x99, 0x99, 0x99)); condfmt[0].setCellFormat(cf); // Condition #2 condfmt[1].setType(com.f1j.ss.ConditionalFormat.eTypeFormula); condfmt[1].setFormula1("iseven($A1)", 0, 0); cf.setFontColor(0xffffff); condfmt[1].setCellFormat(cf); // Condition #3 condfmt[2].setType(com.f1j.ss.ConditionalFormat.eTypeCell); condfmt[2].setFormula1("500", 0, 0); condfmt[2].setOperator(com.f1j.ss.ConditionalFormat .eOperatorGreaterThan); cf=condfmt[2].getCellFormat(); cf.setFontColor(0xff0000); condfmt[2].setCellFormat(cf);

Chapter 9, Formatting cells

149

// Select the range and apply conditional formatting b.setSelection(0, 0, 39, 2); b.setConditionalFormats(condfmt); }

150

Programming e.Spreadsheet Reports

Chapter

10
Chapter 10

Formatting data

This chapter contains the following topics:


s s s s s s s s s s s s s

Setting text direction Formatting numbers Creating custom number formats Setting number format to currency Formatting dates Adding custom formats to the Format Cells dialog Using the TEXT worksheet function correctly Displaying numbers in other than scientific notation Displaying dates in local format Returning formatted text Manipulating worksheet errors Hiding results of formulas that return 0 Using conditional formatting

Chapter 10, Formatting data

151

Formatting numbers
To format numbers, set the number format string using the setValueFormat method. Each format string has four sections: one for positive numbers, one for negative numbers, one for zeros, and one for text. Each section is optional. Sections are separated by semi-colons. These methods require that you use a CellFormat object. For information about using a CellFormat object, see Formatting a cell or range in Chapter 9, Formatting cells.Formatting a cell or range. The e.Spreadsheet API also includes a setValueFormatLocal method which should only be used as a method of preparing e.Spreadsheet to receive a date or number entered by a user in the users local format as input. In most cases not involving user interaction, the setValueFormat method is preferred. For a table listing number formatting parameters used in other languages, see e.Reporting for Multiple Locales.

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Number tab 3 Select a number format category and a format. 4 Choose OK.

Syntax
public void setValueFormat(java.lang.String format)

Parameters
Parameter General 0 # ? . (period) Description General format. Digit placeholder. Pads with zeros Digit placeholder. No padding. Digit placeholder. Pads with spaces Decimal point. Determines how many digits (0s or #s) are displayed on either side of the decimal point. Percentage. Number x 100. % character added. Thousands separator.

% , (comma)

152

Programming e.Spreadsheet Reports

Parameter (continued) E- E+ e- e+ [$DM]

Description (continued) Scientific notation. Displays DM as the currency symbol. Any character(s) may be entered after the dollar sign within brackets to designate as the currency symbol. Display that character. Use \ or "" to display other characters, / for fractions. Fill the cell with the next character. One asterisk per format section. Skip the width of the next character. Display the text inside the quotation marks. Text placeholder. Text replaces the @ format character. Date (single digit where applicable) Date (always double digit) 3-letter day of the week abbreviation Day of the week in text Month value (single digit where applicable) Month value (always double digit) 3-letter month abbreviation Month in text Year (double digit) Year (same as y--double digit) Year (four-digit) Displays the era symbol as a Latin letter in Japanese locale. Displays the first character of an era name in Japanese locale. Displays the full era name in Japanese locale. Displays the full era year in Japanese locale. Displays the full era year with a leading 0 in Japanese locale. Hour number. Displays as a single-digit number (e.g., 1-23) based on a 24-hour clock.

$ - + / ( ) : space * (asterisk) _ (underline) "text" @ d dd ddd dddd m mm mmm mmmm y yy yyy g gg ggg e ee h

Chapter 10, Formatting data

153

Parameter (continued) hh m

Description (continued) Hour number. Displays as a double-digit number (e.g., 01-23) based on a 24-hour clock. Minute number. Displays as a single-digit number (e.g., 0-59) when it appears immediately after the h or hh symbol. Otherwise, it is interpreted as a month number. Minute number. Number with leading zeros (e.g., 00-59) when it appears immediately after the h or hh symbol. Otherwise, it is interpreted as a month number. Second number without leading zeros (e.g., 059). Second number with leading zeros (e.g., 0059). 12-hour time. Total number of hours. Total number of minutes. Total number of seconds. Second number, including fractional part, without leading zeros. Second number, including fractional part, with leading zeros. Displays cell contents in black. Displays cell text in blue. Displays cell text in cyan. Displays cell text in green. Displays cell text in magenta. Displays cell text in red. Displays cell text in white. Displays cell text in yellow. Displays cell text using the corresponding color in the color palette. n is a color in the color palette. Designates a different condition for each of the four format sections.

mm

s ss AM/PM, am/pm, A/P, a/p [h] [m] [s] s.0, s.00, s.000 ss.0, ss.00, ss.000 [Black] [Blue] [Cyan] [Green] [Magenta] [Red] [White] [Yellow] [Colorn]

[conditional value]

154

Programming e.Spreadsheet Reports

Code Examples
Example 1: This example will make positive numbers black with comma separators, negative numbers red with comma separators, hide zeros, and return the indicated text if a user tries to enter non-numeric data. The first line gets the cell format; the other lines set the value and cell formats.
cellformat = jbook1.getCellFormat(); cellformat.setValueFormat("[Black]#,###;[Red]#,###;#;\"Error: Entry must be numeric\""); jbook1.setCellFormat(cellformat);

Example 2: This example will make positive numbers green, negative numbers red, zero yellow and text blue.
cellformat = jbook1.getCellFormat(); cellformat.setValueFormat("[Green];[Red];[Yellow]; [Blue]@"); jbook1.setCellFormat(cellformat);

Example 3: This example will hide positive and negative numbers and show text in blue.
cellformat = jbook1.getCellFormat(); cellformat.setValueFormat(";;;[Blue]@"); jbook1.setCellFormat(cellformat);

Creating custom number formats


You create custom number formats using the setValueFormat method. To apply a custom number format to a cell or range, use the setCellFormat method. Custom formats are saved with the workbook file. See examples below.

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Number tab. 3 Select the Number category. 4 In the Number Format section, type in the custom number format. 5 Choose OK.

Chapter 10, Formatting data

155

Code Example
int irow1 = 0, irow2 = 0, icol1 = 3, icol2 = 3; String strTest = "1-10-99"; String strFormat = "mm/dd/yyyy" ; com.f1j.ss.CellFormat CellFormat1; CellFormat1 = Jbook1.getCellFormat(); CellFormat1.setValueFormat(strFormat); // Format a range jbook1.setCellFormat(CellFormat1, irow1, icol1, irow2, icol2); // Test to see if formatting was applied jbook1.setEntry(0, 0, strTest); jbook1.setColWidthAuto(irow1, icol1, irow2, icol2, true); com.f1j.swing.ss.FormatCellsDlg FrmtDlg = new com.f1j.swing.ss.FormatCellsDlg(jbook1); FrmtDlg.show();

Adding custom formats to the Format Cells dialog


To add custom formats to the Format Cells Dialog, add the custom format to e.Spreadsheet using the e.Spreadsheet object to initialize the Format Cells Dialog objectas shown in the code example above.

Setting number format to currency


Set the number format string to currency using the setValueFormat or setValueFormatLocal method. For more details on formatting numbers in general, see Formatting numbers earlier in this chapter.Formatting numbers. This method requires that you use a CellFormat object. For information about using a CellFormat object, see Formatting a cell or range in Chapter 9, Formatting cells.Formatting a cell or range.

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Number tab 3 Select Currency in the Category frame 4 Choose a currency format from the Number Format frame. 5 Choose OK.

156

Programming e.Spreadsheet Reports

Code Examples
Example 1: This example will format the number to be currency with comma separators and two significant digits to the right of the decimal point. Negative numbers will be red. The first line gets the cell format object; the other lines set the value and cell formats.
cellformat = jbook1.getCellFormat(); cellformat.setValueFormat("$#,##0.00_);[Red]($#,##0.00)"); jbook1.setCellFormat(cellformat);

Example 2: This example will format the number in the users language as currency with comma separators and two significant digits to the right of the decimal point. Negative numbers will be red.
cellformat = jbook1.getCellFormat(); cellformat.setValueFormatLocal("$#,##0.00_);[Red]($#,##0.00)"); jbook1.setCellFormat(cellformat);

Displaying numbers in other than scientific notation


By default, e.Spreadsheet uses scientific notation for numbers over ten digits (>9,999,999,999). To display large numbers in other than scientific notation, use the Format Cells dialog in the e.Spreadsheet Designer or setValueFormat using code.

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Number tab. 3 Select Number under Category. 4 Choose any listed format in the Number Format list box.

Code Example
See code example in Formatting numbers earlier in this chapter.Formatting numbers.

Chapter 10, Formatting data

157

Formatting dates
Showing all four year-digits
To format dates to use four digits, call the setValueFormat or setValueFormatLocal method with a four digit year date format string. Using the setValueFormat method requires that you use a CellFormat object. For information about using a CellFormat object, see Formatting a cell or range earlier in this chapter.Formatting a cell or range. Dates are stored as sequential numeric values, where 1 equals January 1st, 1900 and on through 2,958,465 which equals December 31, 9999.

Using the e.Spreadsheet Designer


1 Type a date in a cell. 2 With the cell selected, choose FormatCells. 3 Select the Number tab. 4 Select Date from the Category frame 5 Choose an available, or create a custom, date format with four digits representing the year (e.g., d-mmm-yyyy). 6 Choose Apply or OK. See available date format parameters in Formatting numbers earlier in this chapter.Formatting numbers.

Code Example
This example will format the number as a date in the form d-mmm-yyyy (22Dec-1900).
cellformat = jbook1.getCellFormat(); // Get the cell format cellformat.setValueFormat("d-mmm-yyyy"); // Set the valueformat jbook1.setCellFormat(cellformat); // Set the cell format

Displaying dates in local format


Normally, e.Spreadsheet finds the local computers locale settings and displays the date, number formatting, and other local features in the local format automatically, without any user or developer intervention. The setValueFormatLocal method should only be used as a method of preparing

158

Programming e.Spreadsheet Reports

e.Spreadsheet to receive a date or number entered by a user in the users local format as input. Using the setValueFormatLocal method to set which number format to display is likely to result in unexpected outcomes. In most cases not involving user interaction, the setValueFormat() method is preferred.

Code Examples
The setValueFormat() method accepts a US-English number format and automatically converts it into the current locale. The setValueFormatLocal() method accepts a localized number format. Calling setValueFormat() and letting e.Spreadsheet work out the localization issues is preferred for two reasons: Example 1: The setValueFormatLocal() method is not compatible across locales. The first line of the following code example works in Germany, the second works in Switzerland, but the two lines are not interchangeable:
setValueFormatLocal("#.##0,00"); // wont work in Switzerland setValueFormatLocal("###0.00"); // wont work in Germany setValueFormat("#,##0.00"); // works everywhere

Example 2 The setValueFormatLocal() method is not compatible across versions of e.Spreadsheet. All lines of the following code work for Germany; the first works in the English version of e.Spreadsheet, the second in the German translation of e.Spreadsheet, but the two lines are not interchangeable:
setValueFormatLocal("dd.mm.yy"); // only works in English version setValueFormatLocal("TT.MM.JJ"); // only works in German version setValueFormat("dd/mm/yy"); // works in all current versions

Displaying Julian dates in standard formats


All dates in e.Spreadsheet are handled in Julian format. Any date entered is automatically converted to Julian format internally. You can, however, format the cell to display the Julian date in a more standard date format. See Formatting numbers earlier in this chapter.Formatting numbers. When you send it to a database, the internal Julian value date gets copied. To have the date display in the database field in a standard format you could either format the date field in the database or enter the date in e.Spreadsheet as text so it is stored as a text string.

Chapter 10, Formatting data

159

Formatting text
Changing fonts
To change the font of a specific range, use getFontName and setFontName. This requires that you use a CellFormat object. For information about using a CellFormat object, see Formatting a cell or range earlier in this chapter.Formatting a cell or range. To change the default font, use getDefaultFontName and setDefaultFontName.

Using the e.Spreadsheet Designer


To change the font of the current selection: 1 Choose FormatCells. 2 Select the Font tab. 3 Change the Font as desired. 4 Choose OK. To change the default font: 1 Choose FormatDefault Font from the Format menu. 2 Change the Font as desired. 3 Choose OK.

Code Examples
Example 1: The following example gets the cell format, sets the font name of the current selection to Arial Black, and sets the cell format.
cellformat = jbook1.getCellFormat(); cellformat.setFontName("Arial Black"); jbook1.setCellFormat(cellformat);

Example 2: The following example sets the default font name to Helvetica using setDefaultFontname.
jbook1.setDefaultFontName("Helvetica");

160

Programming e.Spreadsheet Reports

Formatting fonts
There are ten different setFont methods and ten corresponding getFont and isFont methods included with the e.Spreadsheet API. The methods and their functions are listed in the table below. The getFont and setFont functions require that you use a CellFormat object. You get the CellFormat object and call the getFont and/or setFont function(s) on that object. If you called a setFont function, you must then set the CellFormat to the range. For information about using a CellFormat object, see Formatting a cell or range earlier in this chapter.Formatting a cell or range. The getFontSize method returns and the setFontSize method sets font size in twips (1/20th of a point). To set or return the font size in points, use the getFontSizeInPoints or setFontSizeInPoints methods, or pass the desired point size multiplied by 20 in the setFontSize method. Method setFontBold(boolean) setFontColor(int) setFontItalic(boolean) setFontName(String) setFontOutline(boolean) setFontShadow(boolean) setFontSize(int) setFontSizeInPoints(double) setFontStrikeout(boolean) setFontUnderline(boolean) getFontColor() getFontName() getFontSize() getFontSizeInPoints() isFontBold() isFontItalic() isFontOutline() isFontShadow() Function Sets the bold attribute of the font. Sets the color used to display the font. Sets the italic attribute of the font. Sets the font. Sets the outline attribute of the font. Sets the shadow attribute of the font. Sets the font size in twips. Sets the font size in points. Sets the strikeout attribute of the font. Sets the underline attribute of the font. Returns the color used to display the font. Returns the name of the font. Returns the size of the font in twips. Returns the size of the font in points. Returns whether the font is bold. Returns whether the font is italic. Returns whether the font is outline. Returns whether the font is shadow.

Chapter 10, Formatting data

161

Method (continued) isFontStrikeout isFontUnderline

Function (continued) Returns whether the font is strikeout. Returns whether the font is underline.

To control font formatting in a text area (aka a text box) use the corresponding methods in the com.f1j.ss.GRObject class.

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Font tab. 3 Set the Font, Font Style, Size, Effects, and color 4 Choose OK.

Code Example
This code example gets the CellFormat of the current cell, sets the font to bold, and applies that formatting to the current selection.
cellformat = jbook1.getCellFormat(); // Gets the cell format cellformat.setFontBold(true); // Sets the font to bold jbook1.setCellFormat(cellformat); // Sets the cell format

Making the default font scale proportionally


Changing the default font to a TrueType font will make the font scale proportionally.

Code Examples
This code example sets the default font to Times New Roman 12 point.
jbook1.setDefaultFont("Times New Roman", 12);

Setting text color


Use the setFontColor method to set the text color. Note that font color (the color applied to cell text) foreground color (the color of a pattern when a pattern is applied), and background color (the color that shows through between the lines) are three different things. For more information about setting foreground and background colors and a code example, see Setting cell background color later in this chapter.Setting cell background color.

162

Programming e.Spreadsheet Reports

Using the e.Spreadsheet Designer


1 Choose FormatCells. 2 Select the Font tab. 3 Set the text color in the Color frame. 4 Choose OK.

Code Example
The first line of the code gets the cell format. The other lines set the font color and cell format.
cellformat = jbook1.getCellFormat(); cellformat.setFontColor(jbook1.color2RGB(new java.awt.Color(255,0,0))); jbook1.setCellFormat(cellformat);

Setting text direction


To change the orientation of cell data, use the setOrientation method. This method allows you to set orientation to one of five predetermined orientations or a custom orientation. Text orientation is supported under JDKs 1.2 or greater.

Using the e.Spreadsheet Designer


1 Select the cells in which you want to align the contents. 2 Choose FormatCells. 3 Select the Alignment tab. 4 Specify the desired orientation setting. 5 Clck OK.

Syntax
public void setOrientation(short orientation)

Parameters
Parameter Description

orientation A short indicating the orientation style or degree of rotation:

Chapter 10, Formatting data

163

Parameter

Description Orientation Constants: eOrientationNone eOrientationTopToBottom eOrientationCounterClockwise eOrientationClockwise eOrientationAuto Description: Use the default orientation. Stack characters. Orient vertically, bottom-to-top. Orient vertically, topto-bottom. Orient automatically.

Code Example
This code example sets the data to clockwise orientation.
cf.setOrientation(cf.eOrientationClockwise);

This code example sets the data orientation to 45 degrees.


cf.setOrientation((short) 45);

Returning formatted text


Use the getFormattedText method to return text with formatting.

Code Example
This example formats cell A1 to hold a date, then returns the date formatted exactly as the user sees it.
cellformat = jbook1.getCellFormat(); // Gets the cell format cellformat.setValueFormat("d-mmm-yy"); // Sets the valueformat jbook1.setCellFormat(cellformat); // Sets the cell format // Sets A1s entry to 83924, which will display as 9-Oct-29 jbook1.setEntry(0, 0, "83924"); // Stores what the user sees (9-Oct-29) in variable strTmp strTmp = jbook1.getFormattedText(0, 0);

164

Programming e.Spreadsheet Reports

Setting a validation rule for a range


To set a validation rule for a range, use the setValidationRule method of the CellFormat class and apply it to a range. In the code example below, setting the third and fourth parameters in setValidationRule using the getRow and getCol methods applies the validation rule to the range specified in setSelection relative to the active cell.

Using the e.Spreadsheet Designer


1 Select the range where you want to apply the validation rule. 2 Choose FormatCells. 3 Select the Validation tab. 4 Type the formula for the validation rule in the text box under Rule. 5 Select Apply or OK. The formula for the validation rule applies to each cell of the selected range.

Syntax
public void setValidationRule(Book book, java.lang.String rule, int row, int col)

Parameters
Parameter book rule Description The com.f1j.ss.Book this validation rule will apply to. The validation rule expression, such as "(A1>100)". The cell reference in the expression represents the cell reference relative to the values passed in for the row and col parameters. Using the row and column coordinates as the starting point, the rule adjusts according to the position of the active cell. Relative references will be relative to this row. Relative references will be relative to this column.

row col

Chapter 10, Formatting data

165

Code Example
This code example gets a CellFormat object, and sets the desired selection. The setValidationRule method includes parameters for the book to apply the validation rule to, and the location of the range. The setCellFormat method then sets the cell format for the range.
com.f1j.ss.CellFormat cF; jbook1.setSelection("A1:D5"); cF = jbook1.getCellFormat(); cF.setValidationRule(jbook1.getBook(), "Len(A1)<5", jbook1.getRow(), jbook1.getCol()); jbook1.setCellFormat(cF);

Displaying the contents of one cell in another


To get the contents of the cell three rows down and two rows to the right from cell B2, use the OFFSET function as shown in the example. OFFSET returns the value of a cell that is a given distance from the reference cell (B2 in the example) in the cell where the function is entered (or the cell specified when using the setFormula method in code). Enter positive numbers in the parameters to indicate cells below and to the right of the reference cell; enter negative numbers to indicate cells above and to the left. Also see the entry under OFFSET in the e.Spreadsheet Function Reference.

Using the e.Spreadsheet Designer


Example: To get the contents of the cell 3 rows down and 2 columns to the right of cell B2, type the following formula in the cell where you want to display the result.
=OFFSET(B2, 3, 2)

Code Example
This code returns the contents of the cell 3 rows and 2 columns from cell B2 (cell D5) in the specified cell (A1).
jbook1.setFormula(0, 0, "OFFSET(B2, 3, 2)");

166

Programming e.Spreadsheet Reports

Using the TEXT worksheet function correctly


For the TEXT function to convert a number to text, the original number has to be a number, not text. If you have the in-cell formula = TEXT(A1, "0.00") and cell A1 has the number 07, then the cell will return the text string 7.00. If 07 is not a number, then it will return 07. Also see the entry under TEXT in the e.Spreadsheet Function Reference.

Manipulating worksheet errors


In some cases it is possible to use the IF and ISERROR functions in combination to return something other than a worksheet error (like #DIV/0!).

Using the e.Spreadsheet Designer


To write a formula that will divide cell A1 by cell A2, type and enter the following in a cell:
= IF(A2 <> 0, A1/A2, 0)

If the formula causes an error, it returns 0 (instead of the default #DIV/0!); otherwise, it returns the result of A1/A2.

Code Example
jbook1.setFormula(1, 1, "IF(A2 <> 0, A1/A2, 0)");

Hiding results of formulas that return 0


To prevent formulas from showing zero values, call the setShowZeroValues method with a parameter of false.

Using the e.Spreadsheet Designer


1 Choose FormatSheetProperties from the Format menu. 2 Select the View tab.

Chapter 10, Formatting data

167

3 Deselect Zero Values from the sheet and values frame.

Code Example
jbook1.setShowZeroValues(false); // Dont show zero values

168

Programming e.Spreadsheet Reports

Limitations
Returning different results using getRowHeight and rangeToTwips
Both the getRowHeight and the rangeToTwips methods return the height between the gridlines, but the rangeToTwips method adds the height of one of the gridlines to the number it returns.

Code Example
This example sets the setColWidthUnits method to use twips and sets the width of column 2 to 1300 twips It then uses the getColWidth and rangeToTwips methods to return the column width. Note that the rangeToTwips method returns 1305, adding 5 twips for the gridline.
try { java.awt.Rectangle rect = new java.awt.Rectangle(); jbook1.setColWidthUnits(jbook1.eColWidthUnitsTwips); jbook1.setColWidth(1, 1300); System.out.println(jbook1.getColWidth(1)); //returns 1300 jbook1.rangeToTwips(0, 1, 0, 1, rect); } catch (com.f1j.util.F1Exception err) { }

Returning 1 pixel or 15 twips too many with rangeToTwips


This is the result of including the gridline(s) between cells in the result that the rangeToTwips method returns. e.Spreadsheets implementation of RangeToTwips is to have the cell start at the beginning of one gridline and go to the end of the next grid line. e.Spreadsheet includes both gridlines.

Displaying more than 15 significant digits


The e.Spreadsheet program accurately supports 15 significant digits using the current floating point format. To maintain its compatibility with Microsoft Excel (versions 4, 5, 95, 97 & 2000), which has the same limitation, e.Spreadsheet is constrained to 15 significant digits.

Chapter 10, Formatting data

169

Using setColWidthAuto in classes other than JBook


The e.Spreadsheet method JBook.setColWidthAuto(), which sets the widths of the specified columns to automatically adjust to the largest column entry, may only be used with a JBook or a View.

Exporting worksheets with more than 5,971 formatted cells to Excel


An unlimited number of formatted cells are allowed in e.Spreadsheet worksheets. Excel worksheets allow a limited number of formatted cells (5,971 in most versions of Excel). In worksheets that approach the formatted cells limit, Excel worksheets also restrict further data entry after the memory limitation is met. Workbooks created in e.Spreadsheet that are output in any of the Excel file formats are subject to the same limitations.

170

Programming e.Spreadsheet Reports

Chapter

11
Chapter 11

Working with graphics

This chapter contains the following sections:


s s s s s

Adding graphics objects Manipulating graphics objects Adding and returning values Working with drop-down list boxes Using draw

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

171

Adding graphics objects


Inserting an image into a worksheet
Using the addPicture method to insert an image allows for either storing the image reference to the file or converting the image into a byte array and saving it to a VTS file.

Code Example
Example 1: This example code displays a picture in a worksheet and stores a reference to the picture when saved to a VTS file.
jbook1.addPicture(1.1, 1.1, 3.9, 14.9, new java.net.URL("http://www.f1j.com/newimages/ xml2xls.gif"));

Example 2: This code example converts the picture into a byte array and creates a databased picture when saved to a VTS file.
java.net.URL url = new java.net.URL("http://www.actuate.com/navimages/ home_logo.gif"); java.io.InputStream is = url.openStream(); if (is != null) { java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream(256); byte buf[] = new byte[256]; while (true) { int bytes = is.read(buf); if (bytes < 0) break; if (bytes > 0) os.write(buf, 0, bytes); } jbook1.addPicture(1.1, 1.1, 6.9, 14.9, os.toByteArray()); os.close(); is.close(); }

172

Programming e.Spreadsheet Reports

Using addObject to add graphics objects


Use the addObject method to add arcs, arrows, buttons, charts, checkboxes, dropdown lists, listboxes, radio buttons, text areas, lines, ovals, or rectangles-any graphics object other than an image or polygon. To add an image, see Inserting an image into a worksheet earlier in this chapter.Inserting an image into a worksheet. To add a polygon, see Creating a custom polygon object later in this chapter.Creating a custom polygon object. To allow a user to create a graphics object using the mouse, use the setMode method. For more information about using the setMode method, see Using setMode to draw graphics objects later in this chapter.Using setMode to draw graphics objects.

Syntax
public GRObject addObject(short objectType, double x1, double y1, double x2, double y2)

Parameters
Parameter objectType Description A short indicating the graphics object type: eChart eArc, eLine, eOval, ePolygon, eRectangle eButton, eCheckBox, eDropDown, eListBox, eRadioButton, eText x1 y1 x2 y2 Coordinate of the first anchor point of the object measured in columns from the left edge of the worksheet. Coordinate of the first anchor point of the object measured in rows from the top edge of the worksheet. Coordinate of the second anchor point measured in columns from the left edge of the worksheet Coordinate of the second anchor point measured in rows from the top edge of the worksheet.

Code Examples
Example 1:

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

173

This code example adds an arc at the specified coordinates.


jbook1.addObject(com.f1j.ss.GRObject.eArc, 2, 2, 10, 10);

Example 2: This code example uses the RAND function to generate random data on a worksheet, creates a chart using addObject, and links the chart to the sample data.
// Enter some sample data jbook1.setFormula(0, 0, "RAND()"); jbook1.setSelection("A1:B5"); jbook1.editCopyDown(); jbook1.editCopyRight(); // Create the chart com.f1j.ss.GRChart chart = (com.f1j.ss.GRChart)jbook1.addObject(com.f1j.ss.GRObject.eChart, 1, 1, 7, 15); chart.setLinkRange("A1:B5", true); chart.setTitle("Sample Chart"); chart.setChartType(com.f1j.ss.GRChart.eChartTypeColumn);

Creating a graphics object in the cell a user selects


To create a graphics oject in the cell a user selects, begin by implementing the SelectionChanged interface. Then, within the SelectionChangedEvent object, use the API to create a graphics object attached to the selected cell.

Code Example
Before receiving the SelectionChangedEvent object, the event handler that implements the SelectionChangedListener needs to be registered with the workbook.
jbook1.addSelectionChangedListener(this);

This code example implements the selectionChanged method in the SelectionChangedListener interface, gets the range reference of the first selection, and adds a drop-down list box to the first cell in the selection.
public void selectionChanged(com.f1j.swing.SelectionChangedEvent event) { try { RangeRef RRef = jbook1.getSelection(0);

174

Programming e.Spreadsheet Reports

jbook1.addObject(com.f1j.ss.GRObject.eDropDown, RRef.getCol1(), RRef.getRow1(), RRef.getCol1()+1, RRef.getRow1()+1); } catch (com.f1j.util.F1Exception e) { } }

Using setMode to draw graphics objects


The setMode method allows the user to draw charts and other graphics objects using the mouse by setting the current mode for mouse actions. Use the addObject method to insert graphics objects using code. For information about adding graphics objects using code, see Using addObject to add graphics objects earlier in this chapter.Using addObject to add graphics objects.

Syntax
public void setMode(short mode)

Parameters
Parameter mode Description a mouse action mode constant: eModeNormal eModeLine eModeRectangle eModeOval eModeArc eModeText eModeButton eModePicture eModePolygon eModeDropDown eModeCheckBox eModeChart eModeRadioButton eModeListBox

Code Example
This code sets the current mode for mouse actions to draw a chart.
jbook1.setMode(JBook.eModeChart);

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

175

Adding and formatting charts


e.Spreadsheet includes a complete API for adding and formatting charts. For additional information, see Actuates e.Spreadsheet Division website at www.actuate.com.

Using the e.Spreadsheet Designer


1 Select the range to base the chart on. 2 Choose the Insert Chart button on the Drawing and Forms toolbar or choose InsertChart. 3 Using the mouse, define the area where you want the chart to appear. 4 Set the charts formatting using the Chart Wizard. 5 Click OK.

Code Example
This code example inserts two worksheets, sets sheet 0 to be a chart sheet, createsand adds a GRChart object, and links the chart to a worksheet range.
try { if (object == Chart) { JBook2.insertSheets(0, 1); JBook2.getBook().getSheet(0).setSheetType(Sheet.eSheetTypeChart); JBook2.setSheet(0); com.f1j.ss.GRChart grc = (com.f1j.ss.GRChart)JBook2.addObject(GRObject.eChart, 0, 0, 1, 1); createChart(grc); } void createChart(com.f1j.ss.GRChart c) throws com.f1j.util.F1Exception { // Links the chart to the spreadsheet range // All charting API which can be linked back to the spreadsheet are // set in the GRChart object. Formatting and layout are set in the // ChartModel. c.setLinkRange("Sheet1!$A$1:$B$51", false); // false = series in columns com.f1j.chart.ChartModel cm = c.getChartModel();

Adding a listbox
A list box is a text area listing strings from which a user can choose one or more items. Note that a list box is not the same as a dropdown (also known as a drop-down list box, drop-down list, or pull-down list). Drop downs display

176

Programming e.Spreadsheet Reports

a drop-down bar which drops down a list from which the user chooses a single item. For more information about drop-down listboxes, see Inserting and populating a drop-down list box later in this chapter.Inserting and populating a drop-down list box.

Using the e.Spreadsheet Designer


To add a list box: 1 Choose the Insert Listbox button from the Drawing and Forms toolbar. Or 1 Choose InsertForms ObjectListbox. 2 Using the mouse, define the area where you want the listbox to appear. To name the listbox object: 1 Select the listbox. 2 Choose FormatObject. 3 Type the name for the object in the Name for object n: text area. To link a listbox to a cell 1 Select the listbox. 2 Choose FormatObject. 3 Choose the Options tab. 4 Enter the cell to link to in the Link to Cell text entry area. To set or edit listbox items: 1 Select the listbox. 2 Chose FormatObject. 3 Choose the Options tab. 4 Enter or edit a semi-colon delimited list of items to appear in the list box.

Code Example
This example code creates a listbox graphics object (gro) links the text to cell C6, sets the listbox to allow only one selection at a time, and populates the list box with the numbers 1-9.
public void doGraphicsObjects(JBook b) throws Exception { com.f1j.ss.GRObject gro=b.addObject(com.f1j.ss.GRObject.eListBox, 5, 3, 7.5, 7); gro.setCell(com.f1j.ss.GRObject.eCellText, 2, 5); // Link text to a cell gro.setMultipleSelections(false); // Disallow multiple selections

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

177

for (int i=1;i<10;i++) { gro.addItem("List Item "+i); }

// Populate list box

Adding radio buttons


Where a button provides a kind of switch, a radio button provides a way to register a yes or no response. Radio buttons can be grouped together using the Format Group Objects option. When radio buttons are grouped, users can select only one of the radio buttons in the group.

Using the e.Spreadsheet Designer


To add a Radio Button: 1 Choose the Insert Radio Button button on the Drawing and Forms toolbar. or 1 Choose InsertForms ObjectRadio Button. 2 Using the mouse, define the area where you want the radio button to appear. To name the radio button object: 1 Select the radio button. 2 Choose Format Object to display the Format Object dialog box. 3 Type the name for the object in the Name for object n: text area. To link to a cell 1 Select the radio button. 2 Choose Format Object to display the Format Object dialog box. 3 Select the Options tab. 4 Enter the cell to link to in the Linked to Cell text entry area. To set or edit the caption: 1 Select the radio button. 2 Choose Format Object to display the Format Object dialog box. 3 Select the Options tab. 4 Enter or edit the caption text in the Caption text entry area.

178

Programming e.Spreadsheet Reports

Code Example
This code example creates a group (groGroup) of four radio buttons (groRadio1-4), associates each radio button with the group, then labels them "Radio Button 1-4" using the setText method. Group selection values are then linked to a cell using the setCell method.
public void doGraphicsObjects(JBook b) throws Exception { com.f1j.ss.GRObject groGroup = b.addObject(com.f1j.ss.GRObject.eGroup, 5, 7, 7.5, 10); com.f1j.ss.GRObject groRadio1 = b.addObject(com.f1j.ss.GRObject.eRadioButton, 5, 7, 7.5, 8); com.f1j.ss.GRObject groRadio2 = b.addObject(com.f1j.ss.GRObject.eRadioButton, 5, 8, 7.5, 9); com.f1j.ss.GRObject groRadio3 = b.addObject(com.f1j.ss.GRObject.eRadioButton, 5, 9, 7.5, 10); com.f1j.ss.GRObject groRadio4 = b.addObject(com.f1j.ss.GRObject.eRadioButton, 5, 10, 7.5, 11); groRadio1.setText("Radio Button 1"); groRadio2.setText("Radio Button 2"); groRadio3.setText("Radio Button 3"); groRadio4.setText("Radio Button 4"); groGroup.addObject(groRadio1); groGroup.addObject(groRadio2); groGroup.addObject(groRadio3); groGroup.addObject(groRadio4); groGroup.setCell(com.f1j.ss.GRObject.eCellText, 1, 5); }

Adding a text area


A text area (also known as a text box) is a small word-processing window that provides a convenient way to display formatted text in a worksheet.

Using the e.Spreadsheet Designer


1 Choose the Insert Text Area button on the Drawing and Forms toolbar. or 1 Choose InsertForms ObjectText Area. 2 Using the mouse, define the area where the text area appears.

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

179

To name the text area object: 1 Select the text area. 2 Select FormatObject. 3 Type the name for the object in the Name for object n: text area.

Code Example
This code example adds a text area (groText) using the addObject method, adds text using the setText method, and adds formatting to selected portions of the text using versions of setFontBold, setFontItalic, and setFontSize that take integers that indicate starting and ending positions in the text.
public void doGraphicsObjects(JBook b) throws Exception { com.f1j.ss.GRObject groText = b.addObject(com.f1j.ss.GRObject.eText, 5, 12, 7, 15); groText.setText("This is the initial text for the textbox object"); groText.setFontBold(true, 0, 4); groText.setFontItalic(true, 5, 7); groText.setFontSize(14 * 20, 12, 20); }

Creating a custom polygon object


Use the addPolygon method to create and define placement of a polygon object.

Syntax
public GRObject addPolygon(double x1, double y1, double x2, double y2, java.awt.Point[] points, boolean closed)

180

Programming e.Spreadsheet Reports

Parameters
Parameter x1 y1 x2 y2 points[] closed Description Coordinate of the first anchor point of the object; measured in columns from the left. Coordinate of the first anchor point of the object; measured in rows from the top. Coordinate of the second anchor point; measured in columns from the left. Coordinate of the second anchor point; measured in rows from the top. Array for the x and y points on the polygon. The array can have as few as 2 and as many as 4,096 points. Sets the polygon closed flag. If the flag is true, then the polygon is closed and can be filled.

Code Example
// Creates a java.awt.Point array with 3 points. java.awt.Point[] location = new java.awt.Point[3]; // Sets each point objects x and y values. 16,384 is the maximum width or // height. location[0] = new java.awt.Point(0, 0); location[1] = new java.awt.Point(0, 16384); location[2] = new java.awt.Point(16384, 0); // Describes the polygon using the DGG3RO\JRQ method. This polygon starts in // cell B1 and spans 4 rows and 4 columns jbook1.addPolygon(1, 1, 5, 5, location, true);

Manipulating graphics objects


Setting backgrounds for graphics objects
To use a gradient or texture pattern as a background in a graphics object, use the setPattern method and one of the pattern type parameters in the list below.

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

181

To use a custom pattern or image as a background, use the setPatternURL method and set the path to a GIF, JPG, or PNG file. The textures JAR file, f1jtextures.jar, must be on the class path before you can apply texture backgrounds. For more information about adding files to the class path, see Changing the class path on my machine in Chapter 15, Developing applications.Developing applications. For more information about the contents and location of e.Spreadsheet JAR files, see e.Spreadsheet files in Chapter 19, Additional Information.e.Spreadsheet files. e.Spreadsheet supports patterns when running under Java 2 or or higher. Under Java 1.1, all patterns display as solid.

Using the e.Spreadsheet Designer


1 Place a graphics object on a worksheet. 2 Choose FormatObject. To apply a pattern, gradient, or texture: 3 Select Pattern: or Gradient: in the Format Object dialog. 4 Select the desired pattern or gradient. 5 Choose Apply or OK. To apply a custom pattern or image: 3 Choose the Picture URL: radio button. 4 Type the URL of the pattern or image to use. 5 Choose Apply or OK.

e.Spreadsheet Patterns and Gradients


Gradient Patterns ePatternCenterGradient ePatternHorzGradient ePatternMidDiagGradient ePatternMidHorzGradient ePatternMidVertGradient ePatternRevHorzVertGradient ePatternVertGradient Texture Patterns ePatternDiagGradient ePatternHorzVertGradient ePatternMidGradient ePatternMidRevDiagGradient ePatternRevDiagGradient ePatternRevVertHorzGradient ePatternVertHorzGradient

182

Programming e.Spreadsheet Reports

Gradient Patterns ePatternBlueTissuePaper ePatternBrownMarble ePatternCork ePatternDivot ePatternGranite ePatternLargeConfetti ePatternNewsPrint ePatternPaperBag ePatternParchment ePatternPurpleMesh ePatternSand ePatternStationary ePatternWaterDroplets ePatternWhiteMarble ePatternBouquet ePatternCanvas ePatternDenim ePatternFishFossil ePatternGreenMarble ePatternMediumWood ePatternOak ePatternPapyrus ePatternPinkTissuePaper ePatternRecycledPaper ePatternSolidDiamond ePatternWalnut ePatternWeave ePatternWovenMat

Code Example
This example adds a denim texture pattern to the text box newTextArea.
com.f1j.ss.GRObject newTextArea = jbook1.addObject(com.f1j.ss.GRObject.eText, 2, 2, 10, 10); newTextArea.setPattern(com.f1j.ss.CellFormat.ePatternDenim);

Getting the location of a graphics object


Using the getPos method with the getX1, getX2, getY1, and getY2 methods as shown in the following code example returns the horizontal and vertical starting and ending positions of a graphics object.

Code Example
com.f1j.ss.GRObject newRectangle = jbook1.addObject(com.f1j.ss.GRObject.eRectangle, 2, 2, 10, 10); int X1 = newRectangle.getPos().getX1(); int X2 = newRectangle.getPos().getX2(); int Y1 = newRectangle.getPos().getY1(); int Y2 = newRectangle.getPos().getY2();

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

183

Getting the x, y coordinates of a cell in pixels


The rangeToPixels method returns the offset, width, and height of the specified range in pixels and an index number (1, 2, or 0) indicating whether the range is fully visible, partly visible or not visible. Use the rangeToPixels method to convert the location of the given cell in pixels. Use the rangeToTwips method to return the location in twips. It is possible to use the rangeToPixels method to return the location of a single cell in pixels or the rangeToTwips method to return a single cell location in twips.

Code Example
java.awt.Rectangle sizeInPixels = new java.awt.Rectangle(); jbook1.rangeToPixels(0, 0, 0, 0, sizeInPixels);

Making graphics objects transparent


To make graphics objects transparent, pass 0 (no pattern) to the setPattern method.

Code Example
com.f1j.ss.GRObject newRectangle = jbook1.addObject(com.f1j.ss.GRObject.eRectangle, 2, 2, 10, 10); newRectangle.setPattern(ePatternNull);

Setting size and position using setPos


The setPos method sets the position and size of a graphics object using parameters for the beginning and ending rows and columns of a graphics object.

Syntax
public void setPos(double x1, double y1, double x2, double y2)

184

Programming e.Spreadsheet Reports

Parameters
Parameter x1 y1 Description beginning column beginning row Parameter x2 y2 Description ending column ending row

Code Example
com.f1j.ss.GRObject newRectangle = jbook1.addObject(com.f1j.ss.GRObject.eRectangle, 2, 2, 10, 10); newRectangle.setPos(4,4,10,10);

Selecting graphics objects


To select a graphics object using code, use the setSelection method. To select a graphics object using the e.Spreadsheet Designer, press CTRL while clicking on the object. The setAllowObjectSelections method must be called with true and protection must be turned off.

Using the e.Spreadsheet Designer


1 Ctrl+click the object.

Code Example
// Pass getObject the ID number of the list box. com.f1j.ss.GRObject myobj = jbook1.getObject(1); jbook1.setSelection(myobj);

Preventing users from moving graphics objects


Calling the setAllowObjSelections property with false effectively prevents graphics objects from being moved. If the object cannot be selected, it cannot be moved.

Code Example
book1.setAllowObjectSelections(false);

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

185

Matching cell and graphics object index values


To assign a cell and a graphics object the same index value, set the type parameter of the setCell method to eCellValue. The setCell method assigns a worksheet cell to hold the value displayed by a checkbox, listbox, radio button, dropdown, or group of radio buttons.

Syntax
public void setCell(short type, int row, int col)

Parameters
Parameter type Description Sets the graphics object cell flag. This flag controls what is placed in the cell identified by row and column when a selection is made from the graphics object. Flag eCell eCellValue eCellText Description Cell value is not changed when selection is made from a listbox or dropdown. Cell value is set to index of selection in a listbox or dropdown. Cell value is set to text of selection in a listbox, dropdown or group of radio buttons; true or false in a checkbox or radio button object.

row col

Index numberof row where graphics object value is placed. Index numberof column where graphics object value is placed.

Code Example
try { com.f1j.ss.GRObject test = jbook1.getObject(1); test.setCell(com.f1j.ss.GRObject.eCellValue, 0, 0); } catch (com.f1j.util.F1Exception e1) { }

186

Programming e.Spreadsheet Reports

Setting graphics object colors


To assign a color to a graphics object, select it, use the setPattern method to set the pattern, then use setPatternFG and setPatternBG to set the background and foreground colors. A pattern of none makes the inside of the object transparent. Rectangles, Ovals, Arcs, and Polygons can have colors and patterns. For Swing, the parameter for setPatternBG and setPatternFG is an integer value made up of the Red, Green, and Blue 8-bit values.

Using the e.Spreadsheet Designer


1 Ctrl+click the object to select it. 2 Choose FormatObjectOptions... 3 Select the Fill tab. 4 Select the desired Pattern and Color settings. 5 Choose Apply or OK.

Code Example
try { com.f1j.ss.GRObject test = jbook1.getObject(1); test.setPattern((short)64); test.setPatternBG(0x00ffceff); test.setPatternFG(0x008822aa); } catch (com.f1j.util.F1Exception e1) { }

Deleting a graphics object during runtime


To delete a graphics object, use the getSelectedObject method to return the objects ID number, then use the removeObject method to delete the object.

Using the e.Spreadsheet Designer


1 Ctrl+click the object to select it. 2 Press the Delete key (or choose Cut from the Edit menu).

Code Example
try { jbook1.removeObject(jbook1.getSelectedObject(0)); catch(com.f1j.util.F1Exception e) { }

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

187

Positioning a check box in a column


Use decimal values for the x and y coordinate parameters of the addObject method to adjust the checkboxs position within the column.

Code Example
try { com.f1j.ss.GRObject objCheckbox = jbook1.addObject(com.f1j.ss.GRObject.eCheckBox, 2.4, 1, 2.6, 2); objCheckbox.setName("checkbox"); } catch (com.f1j.util.F1Exception err) { }

Creating a button that loads a VTS file from a local hard drive
To create a button that loads a workbook, follow these four basic steps: 1 Create a workbook and save it to the current local directory. 2 Create a button using the addObject method. Use the setText method to set the button text. 3 Add an ObjectListener. Use the objectClicked method to detect when the button is clicked. 4 Set up the getObject method to return the workbook when the button is clicked.

Code Example
This code will open the file ExpenseReport.vts located in the current local directory.
// This class must implement com.f1j.swing.ObjectListener. try { button1 = jbook1.addObject(com.f1j.ss.GRObject.eButton, 2, 2, 4, 4); button1.setText("Expense Report"); jbook1.addObjectListener(this); } // The other methods for the interface ObjectListener must also be implemented. public void objectClicked(com.f1j.swing.ObjectEvent event1) {

188

Programming e.Spreadsheet Reports

if (event1.getObject() == button1) { try { jbook1.read(System.getProperty("user.dir") + java.io.File.separator + "ExpenseReport.vts", new com.f1j.ss.ReadParams()); } catch(java.io.Exception e) { } } }

Giving a graphics object focus with one click


Normally, when e.Spreadsheet loses focus, it takes one click on e.Spreadsheet to give it focus and another click to manipulate the graphics objects or the active cell. This can be changed by passing eShowOn instead of eShowAutomatic to the setShowSelections method.

Syntax
public void setShowSelections(short ShowFlag)

Parameters
Parameter eShowOff eShowOn eShowAutomatic Description never show always show show when window is active

Using the e.Spreadsheet Designer:


1 Choose FormatSheetProperties. 2 Select the Selection tab. 3 Select On from the Show Selections list. 4 Choose Apply or OK.

Code Example
try { jbook1.setShowSelections(jbook1.eShowOn); } catch (com.f1j.util.F1Exception e) { }

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

189

Showing graphics objects when hiding adjacent cells


In the e.Spreadsheet Designer, holding down the ALT key while inserting a graphics object causes the object to snap to the cell borders of the selected range so that the object will increase or decrease in size as the cell or range size increases or decreases. This causes the objects coordinates to extend into the adjacent column and row to the right of and below the object. When the row or column containing the coordinates is hidden, the object disappears because its coordinates were in that column or row. To correct this, make the object slightly smaller than the cell. The same thing happens when a graphics object is added from code whose right or bottom border is aligned with a column or row border. To prevent this, pass the addObject method a number in the row and column coordinates that is just short of the row and column borders.

Code Example
This code inserts a button in cell B2 that wont touch the border. Hiding column C does not hide the button.
com.f1j.ss.GRObject mygr = jbook1.addObject(com.f1j.ss.GRObject.eButton, 1, 1, 1.99, 2);

Forcing objectClicked and objectDblClicked to fire for graphics objects


In order to make the objectClicked or objectDblClicked methods fire for these objects, the objects must be given a name. This can be done using the e.Spreadsheet Designer or using code. The behavior of the objectClicked and objectDblClicked methods is currently subject to JDK bugs (bugs 10071 and 9163, respectively). Buttons and polygon objects fire the objectClicked event whether they are named or not. After naming them, other objects (like check boxes and list boxes) do not fire the objectClicked event. The objectDblClicked method does not fire for any of the objects. A code example for how it should work is below.

Using the e.Spreadsheet Designer:


1 Place an object on the worksheet. 2 If it is not selected already, Ctrl-click the object. 3 Choose FormatObjectOptions.... 4 Select the Name tab.

190

Programming e.Spreadsheet Reports

5 Type a name in the Name for object x text box. 6 Choose Apply or OK.

Code Example
com.f1j.ss.GRObject objButton = jbook1.addObject(com.f1j.ss.GRObject.eButton, 1, 5, 2, 6); objButton.setName("button");

Adding and returning values


Detecting value changes on graphics object clicks
Use the ObjectEvent class to create an object event that fires when a specific graphics object (such as an arc button, line, oval, square or polygon) is clicked. Note that ObjectEvent does not fire for the drop-down list box or checkbox. The objectValueChanged method notifies the listener when the value of a named checkbox or drop-down list box changes.

Code Example
void objectValueChanged(ObjectEvent e) { try { int i = e.getObject().getValue(); } catch(com.f1j.util.F1Exception e) { } }

Setting values or selections for check boxes or drop-down list boxes


Use the setValue method in the GRObject class. This method sets the state of a checkbox to true (1) or false (0), or sets the selected item in a drop-down list box.

Code Example
The following code creates a new checkbox, sets the caption, and sets the value to 1 or true.
com.f1j.ss.GRObject chkbox1; chkbox1 = jbook1.addObject(com.f1j.ss.GRObject.eCheckBox, 1, 2, 3, 3);

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

191

chkbox1.setText("MyCheckbox"); chkbox1.setValue(1); // Checks the check box. 1 = on/true; 0 = off/false

Getting a graphics object name from the ID number


To get the name of an already named graphics object, use the getName method. The code example below uses the getObject and setName methods to get the object by index number and name it, then uses the getName method to get the name of the object from the ID number.

Code Example
jbook1.getObject(1).setName("Herb"); String n = jbook1.getObject(1).getName();

Getting a graphics object ID from the object name


The getID method returns the object ID for the specified named graphics object.

Code Example
myObject = jbook1.getObject("Herb"); int id = myObject.getID();

Getting information from object events parameters


Use the objectClicked or objectDblClicked methods to get object event information such as the objects name, type and ID number.

Code Example
void objectClicked(ObjectEvent e) { String n = e.getObject().getName(); short s = e.getObject().getType(); int i = e.getObject().getID(); }

192

Programming e.Spreadsheet Reports

Working with drop-down list boxes


Inserting and populating a drop-down list box
Use the addObject method to insert a drop-down list box. Populate it using the addItem or insertItem methods. Remove items using the deleteItem method. The addItem and insertItem methods also allow adding items using a semicolon-delimited list, such as: addItem("Red; Green; Blue; White; Black").

Using the e.Spreadsheet Designer


1 Add a drop-down list box to the worksheet. 2 Ctrl+click to select it. 3 Choose FormatObject. 4 Select the Options tab. 5 Enter the semicolon-delimited list in the Items in List text box. 6 Choose Apply or OK.

Code Example
try { jbook1.addObject(com.f1j.ss.GRObject.eDropDown, 1, 1, 2, 2); com.f1j.ss.GRObject myobj = jbook1.getObject(1); myobj.addItem("Brian"); myobj.insertItem(0, "Ted"); myobj.addItem("Dan"); } catch (com.f1j.util.F1Exception e1) { }

Changing an item in a drop-down list box


Change items in a drop-down list box using the setItem method.

Syntax
public void setItem(int item, java.lang.String itemStr)

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

193

Parameters
Parameter item itemStr Description Identifies the item in the list box by number. Items in a list box are numbered sequentially starting with 0. A string identifying the list box item

Using the e.Spreadsheet Designer


1 Ctrl+click the drop-down list box to select it. 2 Choose FormatObject from the Format menu 3 Select the Options tab. 4 Type the new item over the old one. 5 Choose Apply or OK.

Code Example
try { com.f1j.ss.GRObject test = jbook1.getObject(1); test.setItem(2, "Steve"); } catch (com.f1j.util.F1Exception e1) { }

Displaying an item from a list box in a cell


Use the getObject and setCell methods to display an item from a drop-down list box in a cell. For more information about using the setCell method, see Matching cell and graphics object index values earlier in this chapter.Matching cell and graphics object index values.

Using the e.Spreadsheet Designer


1 Ctrl+click on the drop-down list box to select it. 2 Choose FormatObject. 3 Select the Options tab. 4 Type the cell reference in the Linked to Cell text area. 5 Choose Apply or OK.

Code Example
try {

194

Programming e.Spreadsheet Reports

com.f1j.ss.GRObject test = jbook1.getObject(1); test.setCell(com.f1j.ss.GRObject.eCellText, 0, 0); } catch (com.f1j.util.F1Exception e1) { }

Getting an item out of a drop-down list box


To get an item out of a drop-down list box, set up code in the objectValueChanged method and connect the list box to a cell. Then, call the getObject method with the index number of the drop-down list box, use the getValue method to get the index number of the current selection, and use the getItem method to return the current item. For more information about returning items out of a list box, see Inserting and populating a drop-down list box earlier in this chapter.Inserting and populating a drop-down list box.

Code Example
try { com.f1j.ss.GRObject test = jbook1.getObject(1); String s = test.getItem(test.getValue()); } catch (com.f1j.util.F1Exception e1) { }

Deleting items from a drop-down list box


To delete items from a drop-down list box using code, get the object index number using the getObject method, then remove it using the deleteItem method. The code example below removes the second item from the dropdown list box object list. Object 1 in a zero-based list is the second object.

Using the e.Spreadsheet Designer


1 Ctrl+click on the object. 2 With the object selected, choose FormatObjects. 3 Select the Options tab. 4 Delete the item(s) you want to remove.

Code Example
try { com.f1j.ss.GRObject myobj = jbook1.getObject(1);

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

195

myobj.deleteItem(1); } catch (com.f1j.util.F1Exception e1) { }

196

Programming e.Spreadsheet Reports

Using draw
The draw method draws a workbook to the specified graphics context, such as a printer or window. The draw method should only be used in special cases where you need to customize printing (e.g., when printing multiple components on the same page). See code example below. The draw method is not the recommended method for general printing. Whenever possible, use the filePrint method instead.

Syntax
public void draw(java.awt.Graphics g, int x, int y, int cx, int cy, int nRow, int nCol, int[] rows, int[] cols, int nFixedR1, int nFixedRows, int nFixedC1, int nFixedCols)

Parameters
Parameter g x y cx cy nRow nCol rows[] cols[] nFixedR1 Controls handle to the graphics object for the off screen image starting x coordinate of graphics image in off screen coordinates starting y coordinate of graphics image in off screen coordinates width of the image in off screen coordinates height of the image in off screen coordinates beginning row of the workbook to be drawn - 0 based beginning column of the workbook to be drawn - 0 based number of rows to be drawn number of columns to be drawn beginning fixed row of the drawn worksheet - 0 based

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

197

Parameter nFixedRows nFixedC1 nFixedCols

Controls (continued) number of rows to be fixed in the drawn worksheet beginning fixed column of the drawn worksheet - 0 based number of columns to be fixed in the drawn worksheet

Code Examples
Example 1: This code example uses the draw method with Java 2 to print a JBook.
import java.awt.*; import java.awt.print.*; public class DrawToPrinter extends javax.swing.JComponent implements Printable { com.f1j.swing.JBook jbook1 = new com.f1j.swing.JBook(); public int print(Graphics g, PageFormat pgFormat, int pageIndex) { if (pageIndex > 0) { return Printable.NO_SUCH_PAGE; } pgFormat.setOrientation(PageFormat.PORTRAIT); g.setFont(new Font("Sanserif", Font.PLAIN, 9)); int fontHeight = g.getFontMetrics().getHeight(); int fontDescent = g.getFontMetrics().getDescent(); double pageHeight = pgFormat.getImageableHeight()-fontHeight; double pageWidth = pgFormat.getImageableWidth(); g.translate((int)pgFormat.getImageableX(), (int)pgFormat.getImageableY()); // Simulates header g.drawString("Top Center", (int)(pageWidth/2 - 35), (int)(fontHeight - fontDescent)); try { int[] rowsToPrint = {5}; int[] colsToPrint = {5}; jbook1.setText(0, 0, "Test Print"); // sample text in A1 // Sets desired JBook Page Setup properties

198

Programming e.Spreadsheet Reports

jbook1.setPrintGridLines(true); jbook1.setPrintColHeading(true); jbook1.setPrintRowHeading(true); jbook1.draw(g, // Printer Graphics object 72, // X-coordinate of starting 50, // Y-coordinate of starting point 300, // Width of JBook on printed page 100, // Height of JBook on printed page 0, // First row in JBook to print 0, // First col in JBook to print rowsToPrint, // Number of rows to print colsToPrint, // Number of cols to print 0, // Beginning fixed row - 0 based 0, // Number of fixed rows 0, // Beginning fixed column - 0 based 0 ); // Number of fixed columns } catch (com.f1j.util.F1Exception eJ){ } // Simulates footer g.drawString("Page: " + (pageIndex+1), (int)((pageWidth/2-35)-72), (int)(pageHeight + fontHeight - fontDescent-50)); return Printable.PAGE_EXISTS; } public static void main(String[] args) { PrinterJob myPrintJob = PrinterJob.getPrinterJob(); PageFormat pgFormat = myPrintJob.defaultPage(); myPrintJob.setPrintable(new DrawToPrinter(), pgFormat); try { myPrintJob.print(); } catch (PrinterException e) { } } } }

Example 2: This code example uses the draw method to print a JBook.
import java.awt.*;

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

199

public class DrawToPrinter extends javax.swing.JFrame { com.f1j.swing.JBook jbook1 = new com.f1j.swing.JBook(); public DrawToPrinter() { super(); } public void print() { try { java.awt.PrintJob TheJob = getToolkit().getPrintJob(this, "Print Test", new java.util.Properties()); if (TheJob != null) { java.awt.Graphics g = TheJob.getGraphics(); // Simulates header g.drawString("Header", 30, 50); try { int[] rowsToPrint = {5}; int[] colsToPrint = {5}; jbook1.setText(0, 0, "Test Print"); //sample text in A1 // Sets desired jbook1 Page Setup properties jbook1.setPrintGridLines(true); jbook1.setPrintColHeading(true); jbook1.setPrintRowHeading(true); jbook1.draw(g, // Printer Graphics object 30, // X-coordinate of starting point 170, // Y-coordinate of starting point 300, // Width of JBook on printed page 100, // Height of JBook on printed page 0, // First row in JBook to print 0, // First col in JBook to print rowsToPrint, // Number of rows to print colsToPrint, // Number of cols to print 0, // Beginning fixed row - 0 based 0, // Number of rows fixed 0, // Beginning fixed column - 0 based 0 ); // Number of fixed columns } catch (com.f1j.util.F1Exception eJ) { } // Simulates footer g.drawString("Footer", 30, 600); g.dispose();

200

Programming e.Spreadsheet Reports

TheJob.end(); } } catch (Exception ex) { } } static public void main(String args[]) { DrawToPrinter myPrint = new DrawToPrinter(); myPrint.print(); System.exit(0); }

Using draw to print with no borders or gridlines


Use the setPrintGridLines method to turn the grid lines on or off on printed output. To remove the border outline, turn off the print column headings and print row headings. Do not confuse the setPrintGridLines method with the setShowGridLines method. The setShowGridlines method turns off grid lines for the screen output only.

Code Example
For a code example, see Using draw earlier in this chapter.Using draw.

Using draw to print data in columns to the same page


To print in columns to the same page, use the draw method. Call the draw method several times to print each column amount on the same page, adjusting the row/column offsets and page location.

Code Example
For a code example, see Using draw earlier in this chapter.Using draw.

Using draw to write a workbook to an image file


This technique is illustrated in detail as part of a demo that dynamically generates a chart on Tidestones website at http://www.actuate.com. Follow the Demos link to the Charting Servlet demos.

C h a p t e r 11 , W o r k i n g w i t h g r a p h i c s

201

202

Programming e.Spreadsheet Reports

Part

4
Part 4

Publishing e.Spreadsheet

Part 4, Publishing e.Spreadsheet

203

204

Programming e.Spreadsheet Reports

Chapter

12
Chapter 12

Connecting to external data

This chapter includes the following topics:


s s s s

Introduction and Update Information Setting up a data source Setting up a range Using XML and XSLT

Chapter 12, Connecting to external data

205

Introduction and Update Information


With e.Spreadsheet, you can connect to external data sources using the e.Spreadsheet Designer or from code. You can store external data in characterdelimited, positional text, XML formatted files, or in relational databases such as Oracle, Access or other database management systems (DBMS) that support the Java Database Connectivity interface standard (JDBC). This chapter outlines and explains the data connection and manipulation process from connecting to external data to formatting and displaying data in a spreadsheet range. For detailed information and descriptions of how to connect to and display external data using the e.Spreadsheet Designer, see Part I, Designing and Deploying e.Spreadsheet Reports in Designing e.Spreadsheet Reports.

206

Programming e.Spreadsheet Reports

Report process API architecture

Chapter 12, Connecting to external data

207

Upgrading legacy code


In some previous versions of e.Spreadsheet, the same API was used for creating all data sources regardless of whether they were file or database data sources. e.Spreadsheet now has a separate set of new classes and methods (in the com.f1j.data.query package and others) for creating database data sources and their associated queries. e.Spreadsheet creates File-based data sources using the same classes and methods as in previous versions. This means that no API changes are necessary for legacy projects containing file-based data sources. Projects containing database data sources can continue to use the previous APIs, but developers who want to use the newer functionality, including multiple data queries on a single data source, should convert their projects to use the new APIs described in this article.

File format
The file format for report process information changed in version 9.0 of e.Spreadsheet. Like version 9.0, the current version of e.Spreadsheet reads files from earlier versions and upgrades them to the current file format. Earlier versions of e.Spreadsheet can read the current versions files, but if you use a current file in an earlier version of the program, the data sources, queries, and ranges are not visible or saved in the earlier versions files.

API Changes
Version 9.0 of e.Spreadsheet added many new methods and fields to the report process API. Most of the API added in version 9.0 was added to enable e.Spreadsheet to treat queries as separate objects. Treating queries as separate objects allows for multiple queries on a single data source and adds support for the Document Object Model (DOM) API for accessing XML.

Deprecated API
Previous API Classes: com.f1j.swing.jdbc.JDBCDlg com.f1j.jdbc.JDBCImpl com.f1j.jdbc.JDBCQueryObjImpl None. com.f1j.data.query.DatabaseQuery com.f1j.data.DataQueryCollection, com.f1j.data.query.DataQuery, and com.f1j.data.query.DatabaseQuery Substitute API

208

Programming e.Spreadsheet Reports

Previous API (continued) Interfaces: com.f1j.jdbc.JDBC com.f1j.jdbc.JDBCQueryObj

Substitute API (continued) com.f1j.data.source.JDBC com.f1j.data.source.Query

New Interfaces
Replaced API Interfaces: In previous versions of the software, database queries were attached to the data range API. In the current version, queries are separate objects, enabling multiple queries to exist on a single data source. DataQuery DataQueryCollection New API

DatabaseQuery DatabaseQueryParamCollection DatabaseQueryParameter com.f1j.data.source.DOM

New API in Existing Classes


Replaced API New API DataRange: getColumnNumber() getQuery() getRowNumber() setCellAsText(java.lang.String value) setColumnOutlineCollapsed(boolean collapsed) setRowOutlineCollapsed(boolean collapsed) DataRangeImpl (New API from DataRange) DataRangeCollection: find(java.lang.String name)

Chapter 12, Connecting to external data

209

Replaced API (continued)

New API (continued) get() move(com.f1j.data.query.DataQuery query, DataRange range, Sheet sheet, int row, int column) setDataQuery(DataRange range, DataQuery query) DataRangeIterator: getLock() releaseLock()

endColumnName() startColumnName() setColumnName()

endMetaData startMetaData startFieldInfo() setFieldLabel() endFieldInfo() setFieldName setTableName setFieldLabel setCellHyperlink DataRangeFormatIterator (New API from DataRangeIterator) DataSourceCollection: kDOM

kURL

(use kFile in DataSourceCollection.factory()) com.f1j.data.handler.Handler kInvalid

Source.getCodePage() (previously unexposed) Source.setCodePage() (previously unexposed)

getCodePage() setCodePage()

210

Programming e.Spreadsheet Reports

Replaced API (continued)

New API (continued) com.f1j.data.handler.Text kGeneral kNumber kSkip kText getColumnNames() getColumnDataFormat(int index) getColumnDataFormats() setColumnDataFormat(int index, int formatType) com.f1j.data.handler.DelimitedText

getDelimiter()

getDelimiters() getTextQualifier() isTreatConsecutiveDelimitersAsOne()

setDelimiter(char delimiter)

setDelimiters(java.lang.String delimiters) setTextQualifier(char ch) setTreatConsecutiveDelimitersAsOne(boolean b) com.f1j.data.handler.PositionalText (New API from Text and Handler) com.f1j.data.source.Source getDataQueryCollection() getRefreshIndex()

registerDataRangeListener(D ataRange range)

com.f1j.data.DataRangeCollection.setDataQuery or unregisterDataRangeListener com.f1j.data.DataRangeCollection.setDataSource (DataRange range) setRefreshIndex(int index)

Chapter 12, Connecting to external data

211

Replaced API (continued)

New API (continued) com.f1j.data.source.JDBC getAdvancedConnectionProperties() getJndiName() setAdvancedConnectionProperties(java.util .Properties props) setJndiName(java.lang.String name)

Calling getLock and releaseLock in DataRangeIterator


When calling the DataRangeIterator API directly, developers must call the getLock method before calling the startRange method. To close out the sequence, developers must call the endRange method before calling the releaseLock method. You must call the methods in the following order:
getLock() startRange() startMetaData() startFieldInfo() setTableName() setFieldName() setFieldLabel() endFieldInfo() endMetaData() startRow() startCell() setCell() endCell() endRow() endRange() releaseLock()

e.Spreadsheet manages locks internally in the DataSourceCollection API when the refresh method is called.

Setting connection information with a properties file


You can use a properties file to set data connection and formatting settings. To do this, you use the setDataPipesOverrideFile method in the ReadParams class

212

Programming e.Spreadsheet Reports

to direct the ReadParams object to a .properties file to use when opening a workbook file. This file is also known as a merge file since you can use this file to merge data from different sources into the same range. The .properties file contains data connections and formatting settings information used to change the settings for the current workbook. When you change these settings using a .properties file, the new settings override and permanently replace any existing settings in the workbook. The new settings are saved with the workbook. The properties file works with any type of file that e.Spreadsheet can read-in. This allows e.Spreadsheet to add e.Spreadsheet data and e.Spreadsheets data connection and XSL formatting capabilities to Excel spreadsheets without having to convert the file to VTS format first. To use the setDataPipesOverrideFile method, you must first call one of the Book.read() methods that takes a ReadParams object containing either the full path to the merge file, or a java.util.Properties object that contains the necessary merge properties.

Using {mergefile.dir}
You can set the path to the .properties file by adding the text {mergefile.dir} in the value of any property rather than usint the setDataPipesOverrideProperties method to pass in a java.util.Properties object through the API as descrived above. Adding {mergefile.dir} causes e.Spreadsheet to add the full directory path of the specified properties file to the original value before processing any of the properties. For example, adding {mergefile.dir} after the assignment operator . . .
datasource.file1.filepath={mergefile.dir}\\jim.xml

. . . causes the value of that property to change to c:\stuff\jim.xml (if that properties file is in the c:\stuff directory).

Category Property Syntax


Spreadsheet Parameter

Property Description Spreadsheet parameter value. Required. Must be string, integer, double, date, or currency. If not set, defaults to string. Must be true or false. If not set, defaults to true.

ssparam.<name>

ssparam.<name>.type

ssparam.<name>.strip

Chapter 12, Connecting to external data

213

Category Property Syntax (continued) File Data Source datasource.<name> .file datasource.<name> .filetype datasource.<name> .columnpositions

Property Description Full path or URL to the file. Required. Must be XML or TEXT. Required. Comma-separated list of column positions in ascending order. If this property is set and the filetype=TEXT, then Formula One assumes that the files data is positional text. The character(s) used to delimit the file can be a single character or a string of characters and can contain special characters (e.g., tab = '\t'). If this property is set, the filetype=TEXT, and the columnpositions property is not set, Formula One assumes that the files data is delimited. The character used to qualify text when processing delimited text. Must be a single character. This property is ignored if the data source is a delimited text file. Defaults to nothing. Must be true or false. This property is ignored if this data source is not a delimited text file. Defaults to false. Any one of the following text encodings: ANSI UTF8 UTF16BE UTF16LE

datasource.<name> .characterdelimiter

datasource.<name> .textqualifier

datasource.<name> .treatconsecutivedelimitersasone

datasource.<name>.codepage

214

Programming e.Spreadsheet Reports

Category Property Syntax (continued) datasource.<name>.columnnames .delimiters

Property Description Character or list of characters to be recognized as the delimiters of the columnnames property. If this property is not set, it defaults to ",;:". This property is ignored unless this data source is a positional text file. Delimited list of names to assign to columns. This property is ignored unless this data source is a positional or delimited text file. Comma-delimited list of number formatting to assign to columns (e.g., G,G,N,S,T). This property is ignored unless this data source is a positional or delimited text file. Valid characters include: G General format S Skips the column entirely (including data). T Text format N Number format Only valid if filetype=TEXT. Represents the 0-based row number to start processing from. If not set, defaults to 0.

datasource.<name>.columnnames

datasource.<name>.columntypes

datasource.<name>.startrow

Chapter 12, Connecting to external data

215

Category Property Syntax (continued) datasource.<name>.refreshindex

Property Description This data sources index number in the refresh order. Any number from 0 to 128, or -1 if no specific refresh index is desired. Defaults to -1. Note that lower number values indicate higher placement in the refresh order. Must be true or false. Defaults to false. Must be true or false. Defaults to false. Fully-qualified JDBC driver class name. Required (unless jndi.name property is set). Database URL. Required (unless jndi.name property is set). Database username to use in establishing a connection. Defaults to an empty string. Database password to use in establishing a connection. Defaults to an empty string. Fully-qualified JNDI name of a valid javax.sql.DataSource in the JNDI tree. Required (unless both driver and database are set). This property takes precedence over the .driver and .database properties when all three are set.

datasource.<name>.refreshonopen datasource.<name> .removebeforesave JDBC Data Source datasource.<name>.driver

datasource.<name>.database

datasource.<name>.user

datasource.<name>.password

datasource.<name>.jndi.name

216

Programming e.Spreadsheet Reports

Category Property Syntax (continued) datasource.<name>.refreshindex

Property Description This data sources index number in refresh order. Any number from 0 to 128, or -1 if no specific refresh index is desired. Defaults to -1. Note that lower numbers indicate higher placement in the refresh order. Must be true or false. Defaults to false. Sets an intermediate XML schema option. The asterisk must be replaced with a valid intermediate XML schema option name. The value of the property must be a valid value for the given option. See the setIntermediateXMLOption method in the API for valid options and values.

datasource.<name> .removebeforesave datasource.<name>.intrxmlopt.*

Chapter 12, Connecting to external data

217

Category Property Syntax (continued) datasource.<name> .connectionproperty.*

Property Description Properties that begin this way are extracted, put into a new java.util.Properties object, and passed to the setAdvancedConnectionProperties method. Example:
datasource.test .connectionproperty .username = jim

In this case, the property name extracted to the new java.util.Properties object would be username and the value of the property (jim) would be set as the value of the new username property in the new Properties object. These properties are ignored if the jndi.name property is set. If any of these properties are set, the username and password properties are ignored. JDBC Data Query datasource.<name>.dataquery .<name>.query An SQL Query string or SQL stored procedure call. Required. Indicates whether the query property represents a stored procedure call. Must be set to true or false. Defaults to false. Must be JDBC, XML, or TEXT. Defaults to JDBC.

datasource.<name>.dataquery .<name>.storedprocedure

datasource.<name>.dataquery .<name>.result

218

Programming e.Spreadsheet Reports

Category Property Syntax (continued) datasource.<name>.dataquery .<name>.columnpositions

Property Description Comma-separated list of column positions, in ascending order. If this property is set and the result=TEXT, then Formula One assumes that the data type is positional. The character(s) used to delimit the file can be a single character or a string of characters and can contain special characters (e.g., tab = \t). If this property is set, the filetype=TEXT, and the columnpositions property is not set, Formula One assumes that the files data is delimited. Text qualification character used when processing delimited text. Must be a single character. Defaults to nothing.

datasource.<name>.dataquery .<name>.characterdelimiter

datasource.<name>.dataquery .<name>.textqualifier

datasource.<name>.dataquery Must be true or false. .<name> Defaults to false. .treatconsecutivedelimitersasone datasource.<name>.dataquery .<name>.codepage Any one of the following text encodings: ANSI UTF8 UTF16BE UTF16LE Character or list of characters used as the delimiters of the columnnames property. Defaults to ",;:". Delimited list of names to assign to columns.

datasource.<name>.dataquery .<name>.columnnames .delimiters

datasource.<name>.dataquery .<name>.columnnames

Chapter 12, Connecting to external data

219

Category Property Syntax (continued) datasource.<name>.dataquery .<name>.columntypes

Property Description Comma-delimited list of number formatting to assign to columns (e.g., G,G,N,S,T). Valid characters include: G General format S Skips the column entirely (including data). T Text format N Number format Only valid if filetype=TEXT. Represents the 0-based index number of the row number to start processing from. Defaults to 0. The fetch size to use for this query. Only valid with JDBC 2.X drivers. Defaults to 0, which means the fetch size is driver-managed. This data querys index number in the refresh order. Any number from 0 to 128, or -1 if no specific refresh index is desired. Defaults to -1. Note that lower number values indicate higher placement in the refresh order. Must be true or false. Defaults to false. Sets an intermediate XML schema option. The asterisk must be replaced with a valid intermediate XML schema option name. The value of the property must be a valid value for the given option. See the setIntermediateXMLOption method in the API for valid options and values.

datasource.<name>.dataquery .<name>.startrow

datasource.<name>.dataquery .<name>.fetchsize

datasource.<name>.dataquery .<name>.refreshindex

datasource.<name>.dataquery .<name>.refreshonopen datasource.<name>.intrxmlopt.*

220

Programming e.Spreadsheet Reports

Category Property Syntax (continued) datasource.<name>.dataquery .<name>.parameter .<name|index#>.index

Property Description Query parameter index number. 0-based. Use either a name or an index number in the <name| index#> tag, but not both. If a name is used, the .index part of the property is required. If an index number is used, the .index part is not required. Value of the query parameter. Use either a name or an index number in the <name|index#> tag, but not both. If the property exists in the workbook file, but the value is empty, Formula One assumes that null is the parameters value. Required. The query parameters SQL Type. Use either a name or an index number in the <name|index#> tag, but not both. Required. Must be one of the following: BIT FLOAT CHAR REAL VARCHAR DOUBLE LONGVARCHAR BIGINT NUMERIC TINYINT DECIMAL TIMESTAMP INTEGER DATE SMALLINT TIME Or one of the following four, but only if the outparam property is set to true: BINARY VARBINARY LONGVARBINARY CURSOR

datasource.<name>.dataquery .<name>.parameter .<name|index#>.value

datasource.<name>.dataquery .<name>.parameter .<name|index#>.type

Chapter 12, Connecting to external data

221

Category Property Syntax (continued) datasource.<name>.dataquery .<name>.parameter .<name|index#> .outparam

Property Description Indicates whether this parameter is a stored procedure out parameter. Use either a name or an index number in the <name|index#> tag, but not both. Must be true or false. Defaults to false. Include only one output parameter in a .properties file. Cell location of upper left corner of range; can be a defined name or cell coordinates (e.g., C3). Required. If fully-qulaified location is not specified (e.g. , Sheet1!A1), defaults to first sheet in workbook. Must be one of the following: XSLT PRESERVE CLEAR REPLICATE XML Defaults to PRESERVE. Must be one of the following: INSERTDELETE INSERTCLEAR OVERWRITECLEAR Defaults to INSERTDELETE. Indicates whether to refresh this data range on creation/ merge. Must be true or false. Defaults to false. Indicates whether to fill down formulas. Must be true or false. Defaults to false.

datasource.<name> .[dataquery.<name>.] datarange.<name>.location

Data Range1 datasource.<name> .[dataquery.<name>.] datarange.<name> .formatmode

datasource.<name> .[dataquery.<name>.] datarange.<name> .insertmode

datasource.<name> .[dataquery.<name>.] datarange.<name>.refresh datasource.<name> .[dataquery.<name>.] datarange.<name>.filldown

222

Programming e.Spreadsheet Reports

Category Property Syntax (continued) datasource.<name> .[dataquery.<name>.] datarange.<name>.fieldnames datasource.<name> .[dataquery.<name>.] datarange.<name> .rownumbers datasource.<name> .[dataquery.<name>.] datarange.<name> .columnwidth datasource.<name> .[dataquery.<name>.] datarange.<name>.xslt.file datasource.<name> .[dataquery.<name>.] datarange.<name> .xslt.document datasource.<name> .[dataquery.<name>.] datarange.<name>.xslt.logfile

Property Description Indicates whether to include field names as column headers. Must be true or false. Defaults to false. Indicates whether to include row numbers. Must be true or false. Defaults to false. Indicates whether to adjust column width. Must be true or false. Defaults to true. Full path to XSLT file.

Full contents of XSLT to apply to this range. Ignored if xslt.file property is set. Full path to XSLT log file. If not set, no log file is saved.

1. Use bracketed text (in Data Range items) only when associating a range with a JDBC query. Omit the bracketed text when associating the range with a file data source.

Code Example
In this example, e.Spreadsheet creates a spreadsheet report from an Excel file (c:\sales.xls). Working with a merge file, e.Spreadsheet imports new data into the spreadsheet, recalculates the spreadsheet, then saves it back out as the Excel file sales2.xls. The .properties file used in the example is shown below.
public class MergeFileExample { public static void main(String[] args) { com.f1j.ss.Book book = new com.f1j.ss.BookImpl(); book.getLock(); try { com.f1j.ss.ReadParams rp = new com.f1j.ss.ReadParams(); rp.setDataPipesOverrideFile("c:\\sales.xls.properties");

Chapter 12, Connecting to external data

223

// No need to manually refresh the data source collection via the API. // The data range is set to refresh on creation in the merge file and // refreshes on read after merge file changes are applied to // spreadsheet book.read("c:\\sales.xls", rp); // Writes out the new, updated Excel spreadsheet book.write(null, "c:\\sales2.xls", new com.f1j.ss.WriteParams(com.f1j.ss.Constants.eFileExcel97)); } catch (java.io.IOException e) { System.out.println("Exception: " + e.getMessage()); e.printStackTrace(); } catch (com.f1j.util.F1Exception e) { System.out.println("Exception: " + e.getMessage()); e.printStackTrace(); } finally { book.releaseLock(); } } }

Example merge/properties file


The .properties file overrides any existing settings in the worksheet and replaces them with the ones in the file. This particular file sets the data connection to use an e.Spreadsheet JDBC data source and query to pull data from an Access database (Sales) using the Sun JDBC-ODBC Bridge JDBC driver.
# Create JDBC data source, including the JDBC driver class, database URL, # database username and password datasource.SalesDataSource.driver=sun.jdbc.odbc.JdbcOdbcDriver datasource.SalesDataSource.database=jdbc:odbc:Sales datasource.SalesDataSource.user=TempUser datasource.SalesDataSource.password=TempUserPassword # Create query attached to the above data source, specifying the SQL query # string and the return type as a JDBC result set datasource.SalesDataSource.dataquery.SalesDataQuery.query = SELECT * FROM sales datasource.SalesDataSource.dataquery.SalesDataQuery.result=JDBC # Create data range on the spreadsheet (on Sheet 1 at A3) that will receive # the data from the above query, specifying to refresh on creation

224

Programming e.Spreadsheet Reports

datasource.SalesDataSource.dataquery.SalesDataQuery.datarange .SalesDataRange.location = Sheet1!$A$3 datasource.SalesDataSource.dataquery.SalesDataQuery.datarange .SalesDataRange.refresh = true

Using e.Spreadsheet parameters


Though you create e.Spreadsheet parameters like you create defined name and e.Spreadsheet parameters work similarly to defined names, when developing e.Spreadsheet reports, you create them for use as a tool with SQL and XSLT to provide Actuate e.Report users control over variable input from data sources appearing in reports. Since e.Spreadsheet parameters work like defined names, you can use them as variables within worksheet formulas in the same way that defined names are used. For information about using defined names, see Creating or modifying a defined name in Chapter 5, Manipulating cells.Creating or modifying a defined name. When you use a workbook with e.Spreadsheet parameters as or in a report template file in an Actuate e.Reporting Server, the server requires a separate ROP file. The ROP file saves the e.Spreadsheet and other parameters that are not saved with the workbook file. The Actuate e.Reporting Server generates ROP files for reports generated from simple VTS files used as report templates, but VTS files containing e.Spreadsheet parameters must be deployed together with an ROP. For more information about using e.Spreadsheet files as Actuate e.Spreadsheet report templates, see Designing and Deploying e.Spreadsheet Reports in Designing e.Spreadsheet Reports. The Actuate e.Reporting Server also generates pass-through parameters that supply Actuate server-specific information about running the report, such as host name, host IP address, user, password and ID strings. These parameters are passed-through during report generation and do not persist in the VTS, ROP, or generated XLS file. For more information about using pass-through spreadsheet parameters, see Administering e.Spreadsheet Reports in Chapter 4, Deploying e.Spreadsheet Reports in Designing e.Spreadsheet Reports.

Using the e.Spreadsheet Designer


To add e.Spreadsheet parameters: 1 Choose Inserte.Spreadsheet Parameter. 2 Type the name of the parameter in the Name text area. 3 Select the data type of the parameter from the Type: list.

Chapter 12, Connecting to external data

225

4 Type the parameters default value in the Type: text area. 5 Select Write to .xls file as a defined name. This creates a defined name with the same name in the Excel file generated as output when running this workbook as a report template in an Actuate e.Reporting server. 6 Choose Add to add the parameter. It appears in the parameter list. 7 Choose OK. To save e.Spreadsheet parameter settings in a separate ROP file 1 Choose FileExport Parameter File. 2 Save the file with a .rop extension in the same directory as the VTS file.

Code Example
This code example illustrates how to add a single e.Spreadsheet parameter to a VTS file.
public void insertSpreadsheetParameter(BookModel book, String paramName, String paramValue, boolean strip) { book.setDefinedName(paramName, ParamValue, true, strip, com.f1j.ss.Constants.eParamString); }

Writing Callback classes for use on an Actuate server


Callback classes allow you to execute a custom Java class when you run an e.Spreadsheet report on an Actuate e.Reporting server. Developers typically use a Callback class to add data to a VTS file.

Callback class requirements


The Callback class must:
s s s

be located in the Classpath of the machine where it is run. implement the com.f1j.ss.BookModelCallback interface override the callback method

226

Programming e.Spreadsheet Reports

The object provided by this interface is a com.f1j.ss.BookModelImpl object. This interface enables you to modify the data as you would using the graphical user interface.

Executing a Callback class


There are two ways to execute a Callback class.
s

From the report server You execute a Callback class from the report server by entering the class name as the value of the AC_SS_POPULATION_CLASS report parameter. The string you supply for this parameter is the fully qualified class name of the JAVA class implementing the com.f1j.ss.BookModelCallback interface, used to populate the worksheet. These classes conform to the e.Spreadsheet API requirements.

From the e.Spreadsheet Designer Executing a Callback class from the e.Spreadsheet Designer is generally done for testing, to ensure the Callback class populates the worksheet correctly before you save and run the workbook.

Using the e.Spreadsheet Designer


You can run a Callback class for testing purposes as shown below. 1 Type ALT+F11. Execute Callback Class appears.

2 Type the name of the Java Callback class you want to run. The class must be on the classpath. 3 Choose OK. e.Spreadsheet Designer executes the Callback class.

Code Example
This simple Callback class adds a formula to all the cells in the worksheet range A1:E5.
import com.f1j.ss.*; import com.f1j.swing.*;

Chapter 12, Connecting to external data

227

public class CallBackEx implements BookModelCallback{ public void callback(com.f1j.ss.BookModel bk){ try { for(int r = 0; r < 5; r++) { for(int c = 0; c < 5; c++) { bk.setEntry(r,c,"=ADDRESS(ROW(),COLUMN(),1)"); } } } catch(Exception e){ e.printStackTrace(); } } }

Using Callback classes on the reporting server


Callback classes should be saved on the reporting server in an accessible directory. The path to the directory where Java class files are saved should be added to the e.Spreadsheet parameter AC_JDRV_CLASSPATH parameter for the e.Spreadsheet file type(s) that you use (VTS, VTF, or both). Note that the AC_JDRV_CLASSPATH parameter is set per file type, not per report. The server does some automatic processing on the workbook when it runs the report, so you do not have to include procedures for performing those tasks in your callback class. When the server runs the report, it does the following:
s s s s s

Reads in the workbook Sets all of the e.Spreadsheet parameters attached to the workbook Executes the callback class Refreshes all data sources in the workbook. Saves the report as an Excel file

Setting HTTP basic authentication in a data source


When using a Java 2 version 1.3 or higher Runtime Environment, developers can set basic HTTP authentication in the same way authentication is set in most popular browsers. When an HTTP URL to an Actuate e.Report is used as a file data source, which is usually done to add XML from the Actuate e.Report, the Actuate e.Report server stops the report generation process and,

228

Programming e.Spreadsheet Reports

depending on server security settings, returns a security notification. Adding basic HTTP authentication makes it possible to run reports with a URL data source on Actuate servers and allows access to other URL data sources previously unavailable because of authentication issues.

Code example:
File file = (File) book.getDataRangeCollection().factory("test", DataSourceCollection.kFile); file.setFilePath("http://username:pwd@servername/directory/file.xml");

Setting up a data source


Creating a connection to a database data source
This article deals with connecting e.Spreadsheet to a supported SQL database. For information about connecting to a delimited or fixed-width text file, see Creating a data source connection to a file later in this chapter.Creating a data source connection to a file. To connect e.Spreadsheet to an external database, use methods from the DataSourceCollection, Source, DataQueryCollection, DataQuery and DatabaseQuery classes. The code example below uses both the DataSourceCollection class factory() method and the DataRangeCollection class factory() method. The DataSourceCollection class factory() method constructs the data source as described below. The DataRangeCollection class factory() method sets up the data range by setting the name for the range and establishing the location of the first row and column to receive the data. For more information, see Creating a data range later in this chapter.Creating a data range. The factory() method in the DataSourceCollection interface creates the data source. Various methods from the Source.JDBC class specify the JDBC connection information. Once e.Spreadsheet has constructed the basic data source and added it to the list of sources available to the workbook, the data source, query and range are configured using the:
s s s

setDataHandlerType method to set the data handler getXSLTDocument method (optional) to set the XSL stylesheet setCellFormattingMode method to set the formatting mode

Chapter 12, Connecting to external data

229

The getDataRangeCollection and factory methods in the DataRangeCollection interface set the worksheet range. The setDataQuery method connects the data source and query to the range in the workbook. To connect to an Oracle, Access, or any other database using a management system that works with JDBC (Java Data Base Connectivity), change the driver string and the connection URL to match the DBMS of the database. Otherwise, all database connections work in the same way.

Using the e.Spreadsheet Designer


1 Choose DataData Manager to open the Data Manager. 2 Select the Databases folder. 3 Select Add Source to open Data Wizard - JDBC Data Source. 4 Type a name in Data Source Name. (This can be any name.) 5 In Driver Class Name, type the driver name for the database software associated with the database. 6 In Connection URL, type the URL for the database in the indicated format:
jdbc:<subprotocol>:<subname>

where: <subprotocol> is the name of the driver, and <subname> is the name of the database (e.g., jdbc:odbc:Sales). 7 Type a user name and password in the appropriate windows if assigned or required by the database. 8 Choose Next to open the Query dialog. 9 Select the appropriate data type from the Data Type associated with the Data Source list: JDBC Result Set, Text, or XML.

Syntax
public Source factory(java.lang.String name, int sourceType)

Parameters
Parameter name sourceType Description The symbolic name of the created data source. Must be unique within this collection. An integer or short representing the type of the created data source:

230

Programming e.Spreadsheet Reports

Parameter

Description kFile kJDBC kInputStream kDOM Creates a file data source. Creates a JDBC data source. Creates an input stream data source., Creates a Document Object Model data source.

Code Example
This code creates a data source connection abc, between the database and the worksheet data range, test. Beginning at cell A1, the code formats the data using an XSL stylesheet and outputs the file in Excel 8/9 (Office97/2000) file format. The XSL stylesheet used to format the data range follows the code example.
// Creates a new instance of a e.Spreadsheet workbook. com.f1j.ss.BookModelImpl BMI = new com.f1j.ss.BookModelImpl(); BMI.getLock(); try { BMI.initWorkbook(); // Gets the data source from the JBook. com.f1j.data.source.JDBC j_DataSource = (com.f1j.data.source.JDBC) BMI.getDataSourceCollection().factory("abc", com.f1j.data.DataSourceCollectionImpl.kJDBC); j_DataSource.setDriverName("sun.jdbc.odbc.JdbcOdbcDriver"); // DB driver j_DataSource.setDatabase("jdbc:odbc:Sales"); // connection URL j_DataSource.setUserName("sa"); // username j_DataSource.setPassword("sa_password"); // password // Create a data query. com.f1j.data.query.DataQuery j_DataQuery = j_DataSource.getDataQueryCollection().factory("abcQuery"); // Sets data handler for the query. j_DataQuery.setDataHandlerType(com.f1j.data.handler.Handler .kJDBCResultSet); // Tells data source the query. ((com.f1j.data.query.DatabaseQuery)j_DataQuery) .setQuery("select * from Sales", false);

Chapter 12, Connecting to external data

231

// Gets data range from the JBook. com.f1j.data.DataRange d_DataRange = BMI.getDataRangeCollection(0).factory("test", 0, 0); // Connects data query to data range. BMI.getDataRangeCollection(0).setDataQuery(d_DataRange, j_DataQuery); // Gets XSLT document to use for formatting. com.f1j.data.XSLTDocument XSLT = d_DataRange.getXSLTDocument(); // Sets XSLT file path. XSLT.setDocumentPath("c:\\shared\\DBSalesPeople.xsl"); // Tells data range that XSLT document will format. d_DataRange.setCellFormattingMode (com.f1j.data.DataRange.eCellFormatting_XSLT); // Refreshes data range. j_DataSource.getDataQueryCollection().refresh(); // Recalculates since book contents changed. BMI.recalc(); // Writes JBook to output stream in Excel file format. BMI.write(new java.io.FileOutputStream("c:\\salesReport.xls"), new com.f1j.ss.WriteParams(com.f1j.ss.Constants.eFileExcel97)); } catch(Throwable e) { System.out.println(e.getMessage()); } finally { BMI.releaseLock(); }

XSLT Stylesheet Example


<?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl ="http://www.w3.org/1999/XSL/Transform"> <xsl:template name="sell" match="Salesman"> <xsl:param name="region">Midwest</xsl:param> <row defined-name="{$region},salesmen" outline="1" height="20"> <cell><xsl:value-of select="Name" /></cell> <cell defined-name="Jan" outline="1"> <xsl:value-of select="January" /></cell> <cell defined-name="Feb" outline="1">

232

Programming e.Spreadsheet Reports

<xsl:value-of select="February" /></cell> <cell defined-name="Mar" outline="1"> <xsl:value-of select="March" /></cell> <cell defined-name="Qone" font-bold="true" formula="sum(Jan:Mar)" /> <cell defined-name="Apr" outline="1"> <xsl:value-of select="April" /></cell> <cell defined-name="May" outline="1"> <xsl:value-of select="May" /></cell> <cell defined-name="Jun" outline="1"> <xsl:value-of select="June" /></cell> <cell defined-name="Qtwo" font-bold="true" formula="sum(Apr:Jun)" /> <cell defined-name="Jul" outline="1"> <xsl:value-of select="July" /></cell> <cell defined-name="Aug" outline="1"> <xsl:value-of select="August" /></cell> <cell defined-name="Sep" outline="1"> <xsl:value-of select="September" /></cell> <cell defined-name="Qthree" font-bold="true" formula="sum(Jul:Sep)" /> <cell defined-name="Oct" outline="1"> <xsl:value-of select="October" /></cell> <cell defined-name="Nov" outline="1"> <xsl:value-of select="November" /></cell> <cell defined-name="Dec" outline="1"> <xsl:value-of select="December" /></cell> <cell defined-name="Qfour" font-bold="true" formula="sum(Oct:Dec)" /> <cell font-bold="true" formula="Qone + Qtwo + Qthree + Qfour" /> </row> </xsl:template> <xsl:template name="subs"> <xsl:param name="subRegion">Midwest</xsl:param> <xsl:param name="label">Totals</xsl:param> <row> <cell font-bold="true"> <xsl:value-of select="($label)" /> </cell> <cell absolute-defined-name="Jan{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Feb{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Mar{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Apr{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="May{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Jun{$subRegion}" font-bold="true"

Chapter 12, Connecting to external data

233

formula="sum({$subRegion})" /> <cell font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Jul{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Aug{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Sep{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Oct{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Nov{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell absolute-defined-name="Dec{$subRegion}" font-bold="true" formula="sum({$subRegion})" /> <cell font-bold="true" formula="sum({$subRegion})" /> <cell font-bold="true" formula="sum({$subRegion})" /> </row> <row /> </xsl:template> <xsl:template match="/"> <range> <row> <cell /> <cell font-bold="true">Jan</cell> <cell font-bold="true">Feb</cell> <cell font-bold="true">Mar</cell> <cell font-bold="true">Q1</cell> <cell font-bold="true">Apr</cell> <cell font-bold="true">May</cell> <cell font-bold="true">Jun</cell> <cell font-bold="true">Q2</cell> <cell font-bold="true">Jul</cell> <cell font-bold="true">Aug</cell> <cell font-bold="true">Sep</cell> <cell font-bold="true">Q3</cell> <cell font-bold="true">Oct</cell> <cell font-bold="true">Nov</cell> <cell font-bold="true">Dec</cell> <cell font-bold="true">Q4</cell> <cell font-bold="true">Grand Totals</cell> </row> <row outline="1"> <cell font-bold="true">North Region</cell> </row> <xsl:for-each select="/range/row[Region=North]"> <xsl:call-template name="sell">

234

Programming e.Spreadsheet Reports

<xsl:with-param name="region">North</xsl:with-param> </xsl:call-template> </xsl:for-each> <xsl:call-template name="subs"> <xsl:with-param name="subRegion">North</xsl:with-param> <xsl:with-param name="label">North Region Totals</xsl:with-param> </xsl:call-template> <row outline="1"> <cell font-bold="true">East Region</cell> </row> <xsl:for-each select="/range/row[Region=East]"> <xsl:call-template name="sell"> <xsl:with-param name="region">East</xsl:with-param> </xsl:call-template> </xsl:for-each> <xsl:call-template name="subs"> <xsl:with-param name="subRegion">East</xsl:with-param> <xsl:with-param name="label">East Region Totals</xsl:with-param> </xsl:call-template> <row outline="1"> <cell font-bold="true">South Region</cell> </row> <xsl:for-each select="/range/row[Region=South]"> <xsl:call-template name="sell"> <xsl:with-param name="region">South</xsl:with-param> </xsl:call-template> </xsl:for-each> <xsl:call-template name="subs"> <xsl:with-param name="subRegion">South</xsl:with-param> <xsl:with-param name="label">South Region Totals</xsl:with-param> </xsl:call-template> <row outline="1"> <cell font-bold="true">West Region</cell> </row> <xsl:for-each select="/range/row[Region=West]"> <xsl:call-template name="sell"> <xsl:with-param name="region">West</xsl:with-param> </xsl:call-template> </xsl:for-each> <xsl:call-template name="subs"> <xsl:with-param name="subRegion">West</xsl:with-param> <xsl:with-param name="label">West Region Totals</xsl:with-param> </xsl:call-template> <xsl:call-template name="subs"> <xsl:with-param name="subRegion">salesmen</xsl:with-param> <xsl:with-param name="label">Grand Totals</xsl:with-param> </xsl:call-template>

Chapter 12, Connecting to external data

235

</range> </xsl:template> </xsl:stylesheet>

Querying a database
e.Spreadsheet supports all types of SQL queries that retrieve data from the database, including:
s s

standard SQL SELECT statements, data retrieval SQL statements written in database-specific SQL dialects (note that the JDBC driver must support this), and stored procedure calls.

Using the e.Spreadsheet Designer


1 Complete the steps required to connect to a database as listed in Creating a connection to a database data source earlier in this chapter.Creating a connection to a database data source. 2 Choose Next to open Data Wizard - Construct Query. The available database tables appear in Tables. 3 Select one of the tables listed in the tables window to see the fields associated with it. 4 In Query, enter an SQL query describing the tables and fields to connect to. This example query returns all of the fields in the specified table:
select * from <name of DB Table>

5 Choose the data sources data type, JDBC Resultset, Text, or XML, from the Data Type list. 6 Choose Finish.

Syntax
public void setQuery(java.lang.String query)

Parameter
Parameter query Description an SQL query beginning with the SQL select command, describing the tables and fields to connect to.

236

Programming e.Spreadsheet Reports

Code Example
The setQuery method is called on com.f1j.data.query.DatabaseQuery. In earlier versions the setQuery method was called on com.f1j.data.source.Query, which is now deprecated.
// Tells data query the SQL query string. ((com.f1j.data.query.DatabaseQuery)j_DataQuery) .setQuery("select * from Sales");

Creating a data source connection to a file


Creating a connection to a text file works much the same as creating a database connection. You do two things differently. First, when setting up a connection to a file data source, you set the DataSourceCollection interface factory class to use a file as a source. Second, you omit the code that sets up the database driver, mode, and query. For information about creating a database connection, see Creating a connection to a database data source earlier in this chapter.Creating a connection to a database data source.

Using the e.Spreadsheet Designer


1 Choose DataData Manager. 2 Select the Files folder. 3 Choose Add Source to open Data Wizard - File Data Source. 4 Type a name in the Data Source name entry area. (This can be any name.) 5 Type the pathname of the data file in the File Path entry area (e.g., c:\ datafiles\testfiles.txt) or click the Browse button and navigate to and select the file. 6 Select the data type associated with the file from the Data Type list: Text or XML. 7 Choose Finish.

Code Example
This code example:
s

creates a data source connection between the file abc and the worksheet data range test beginning at cell A1 formats the data using XSLT outputs the file in Excel 8/9 (Office97/2000) file format

s s

Chapter 12, Connecting to external data

237

The stylesheet referred to in this example is the same stylesheet used in Creating a connection to a database data source earlier in this chapter.Creating a connection to a database data source.
// Creates a new instance of a e.Spreadsheet workbook. com.f1j.ss.BookModelImpl BMI = new com.f1j.ss.BookModelImpl(); BMI.getLock(); try { BMI.initWorkbook(); // Gets Datasource collection from JBook and stores in file. com.f1j.data.source.File f_DataSource = (com.f1j.data.source.File) BMI.getDataSourceCollection().factory("abc", com.f1j.data.DataSourceCollectionImpl.kFile); // Tells the data source collection which file to use. f_DataSource.setFilePath("c:\\shared\\SalesPeople.xml"); // -OR- could alternately use a URL: // f_DataSource.setFilePath("http://localhost/data/SalesPeople.xml"); // Initializes the data handler for an XML file. f_DataSource.setDataHandler(com.f1j.data.handler.Handler.kXML); // Gets Datarange collection from JBook and stores in data range. com.f1j.data.DataRange d_DataRange = BMI.getDataRangeCollection(0).factory("test", 0, 0); // Connects data source to data range. BMI.getDataRangeCollection(0).setDataSource(d_DataRange, f_DataSource); // Gets XSLT document to use for formatting. com.f1j.data.XSLTDocument XSLT = d_DataRange .getXSLTDocument(); // Sets XSLT file path. XSLT.setDocumentPath("c:\\shared\\SalesPeople.xsl"); // Tells data range that XSLT document will format. d_DataRange.setCellFormattingMode (com.f1j.data.DataRange.eCellFormatting_XSLT); // Refreshes JBook data. BMI.getDataSourceCollection().refresh(); // Recalculates since book contents changed. BMI.recalc();

238

Programming e.Spreadsheet Reports

// Writes JBook to output stream in Excel file format. BMI.write(new java.io.FileOutputStream("c:\\salesReport.xls"), new com.f1j.ss.WriteParams(BMI.eFileExcel97)); } catch(Throwable e) { System.out.println(e.getMessage()); } finally { BMI.releaseLock(); }

Using {paramname}.txt in the file path


When setting the path to a data file in the Data Manager or in a .properties file, adding the text {paramname}.txt in the string that represents the URL or path to the file causes e.Spreadsheet to substitute the e.Spreadsheet parameter or defined name in the path to the data file location every time the file is accessed. e.Spreadsheet replaces the text {paramname} with the value of the e.Spreadsheet Parameter or defined name paramname, as evaluated by the e.Spreadsheet engine. This allows users to pass e.Spreadsheet parameters or defined names on the URL to file data sources.

Working with character-delimited data source files


e.Spreadsheet can establish a data connection with character-delimited and fixed-width (positional text) text files. You can set which source row to begin importing from, the delimiter(s), column data formatting, and column names during the data connection and conversion process. This article describes working with character-delimited files. Working with positional text is discussed in Working with positional text data source files later in this chapter.Working with positional text data source files.

Using the e.Spreadsheet Designer


1 Complete the first five steps required to connect to a file as listed in Creating a data source connection to a file earlier in this chapter.Creating a data source connection to a file. 2 Choose Next in the Data Wizard. Text Data Source Type appears. 3 Select Delimited. 4 Select the row to start the the import from. 5 Choose the type of text encoding used in Code Page. This is optional. 6 Choose Next.

Chapter 12, Connecting to external data

239

The data appears in the data preview window with tab as the default delimiter character. 7 Select one or more delimiters: Tab, Semicolon, Comma, Space, or Others. The data in the preview window displays how the data looks with the chosen delimiter(s). 8 Select Treat consecutive delimiters as one if the data has multiple consecutive delimiters (e.g. ,, in data that uses commas for the delimiter) that should be treated as one delimiter. 9 Choose Next to open the Text Format Options dialog. 10 Format columns as described in Adding column names when importing text data later in this chapter.Adding column names when importing text data. 11 Click Finish.

Code Example
This code example sets up a data connection with a delimited-text file.
jBook.getLock(); try { jBook.initWorkbook(); com.f1j.data.source.File f_DataSource = (com.f1j.data.source.File)jBook.getBook().getDataSourceCollection() .factory("SourceName", com.f1j.data.DataSourceCollectionImpl.kFile); f_DataSource.setFilePath("c:\\shared\\delimitedSP.txt"); f_DataSource.setDataHandler(com.f1j.data.handler.Handler .kDelimitedText); ((com.f1j.data.handler.DelimitedText) f_DataSource.getDataHandler()).setDelimiters(";:,"); ((com.f1j.data.handler.Text)f_DataSource.getDataHandler()).setStartRow(2); com.f1j.data.DataRange d_DataRange = jBook.getDataRangeCollection(0).factory("test", 0, 0); jBook.getDataRangeCollection(0).setDataSource(d_DataRange, f_DataSource); com.f1j.data.XSLTDocument XSLT = d_DataRange.getXSLTDocument(); XSLT.setDocumentPath("c:\\shared\\DLtest.xsl"); d_DataRange.setCellFormattingMode(com.f1j.data.DataRange .eCellFormatting_XSLT);

240

Programming e.Spreadsheet Reports

jBook.getDataSourceCollection().refresh(); jBook.recalc(); } finally { jBook.releaseLock(); }

Working with positional text data source files


e.Spreadsheet can establish a data connection with character-delimited and fixed-width (positional text) text files. For positional text files, you set the row to begin importing from, the separation locations for each field, column data formatting, and column names during the import and conversion process. This article describes working with importing fixed-width files. For information about character-delimited text sources, see Working with character-delimited data source files earlier in this chapter.Working with character-delimited data source files.

Using the e.Spreadsheet Designer


1 Complete the first five steps required to connect to a file as listed in Creating a data source connection to a file earlier in this chapter.Creating a data source connection to a file. 2 Choose Next in the Data Wizard. Text Data Source Type appears. 3 Select Fixed Width. 4 Select the row to start the import from. 5 Choose the type of text encoding used in Code Page. This is Optional. 6 Choose Next Positional Text appears displaying a representation of the data in the source file. Use the mouse to indicate where breaks between the fields occur. The scale across the top indicates number of characters. 7 Choose Next to open the Text Format Options dialog. 8 Format columns as described in Adding column names when importing text data, below.Adding column names when importing text data. 9 Choose Finish.

Code Example
This code example:
s

sets up an integer array for positional file break points

Chapter 12, Connecting to external data

241

creates a file data source named SourceName pointing to c:\shared\ positionalSP.txt configures the data handler with the break points and starting row creates and configures a data range to use XSLT formatting connects to the data source.
int[] breaks = { 6, 17, 24, 31, 38, 45, 52, 59, 66, 73, 80, 87, 94 }; jBook.getLock(); jBook.initWorkbook(); com.f1j.data.source.File f_DataSource = (com.f1j.data.source.File) jBook.getDataSourceCollection().factory("SourceName", com.f1j.data.DataSourceCollectionImpl.kFile); f_DataSource.setFilePath("c:\\shared\\positionalSP.txt"); f_DataSource.setDataHandler(com.f1j.data.handler.Handler.kPositionalText); ((com.f1j.data.handler.PositionalText) f_DataSource.getDataHandler()).setDataPositions(breaks); ((com.f1j.data.handler.Text) f_DataSource.getDataHandler()).setStartRow(3); com.f1j.data.DataRange d_DataRange = jBook.getDataRangeCollection(0).factory("test", 0, 0); jBook.getDataRangeCollection(0).setDataSource(d_DataRange, f_DataSource); com.f1j.data.XSLTDocument XSLT = d_DataRange.getXSLTDocument(); XSLT.setDocumentPath("c:\\shared\\DLtest.xsl"); d_DataRange.setCellFormattingMode(com.f1j.data.DataRange .eCellFormatting_XSLT); jBook.getDataSourceCollection().refresh(); jBook.recalc(); jBook.releaseLock();

s s s

242

Programming e.Spreadsheet Reports

Adding column names when importing text data


For data imported from a file, e.Spreadsheet provides options for applying number formatting and column names during the import using the setColumnName method.

Using the e.Spreadsheet Designer


1 Complete the steps required to connect to a database or file as listed in Creating a connection to a database data sourceCreating a connection to a database data source or Creating a data source connection to a file earlier in this chapter.Creating a data source connection to a file. 2 Choose DataData Manager. 3 Select an existing file data source and choose Edit. 4 Complete the dialogs dealing with data source and delimited text as described in Working with character-delimited data source files earlier in this chapter.Working with character-delimited data source files. 5 Choose Next. Text Format Options appears. 6 Select a column in the data preview window. 7 In Name, type a name for the selected column. 8 Select the data type for the column, General, Number, or Text. Choose the Do not import (skip) button to have e.Spreadsheet ignore the column, including both formatting and data. 9 Repeat steps 6 through 8 for the each column. 10 Choose Finish

Code Example
This code example sets the column name of the first column (column 0) to Region for the delimited or positional data source named j_DataSource.
// Sets column name for delimited or positional data source. com.f1j.data.handler.Text t_handler = (com.f1j.data.handler.Text) j_DataSource.getDataHandler(); t_handler.setColumnName(0, Region);

Setting data source refresh options


You must refresh before any changes to database connections or formatting take effect and become visible on a worksheet. Setting the data source refresh options sets:

Chapter 12, Connecting to external data

243

s s

whether the data refreshes when the workbook is opened whether the connection information is saved with the worksheet

The setInsertMode method in the DataRangeImpl class controls how data is replaced in the worksheet range. For more information, see Setting data range properties later in this chapter.Setting data range properties. In order to immediately see the results of a refresh, call one of the refresh methods or use the Refresh or Refresh All command from the e.Spreadsheet Designers Data menu. For more information, see Refreshing source data later in this chapter.Refreshing source data.

Using the e.Spreadsheet Designer


1 Choose DataData Manager. 2 Select an existing database or file or create a new one following the directions in Creating a connection to a database data sourceCreating a connection to a database data source or Creating a data source connection to a file earlier in this chapter.Creating a data source connection to a file. 3 Choose Edit to open the Data Wizard. 4 Choose Refresh Options to open the Data Source Options window. 5 Select or deselect the desired checkboxes to set whether to refresh on open and whether to remove the data source from the sheet prior to saving. 6 Choose OK.

Code Examples
This code example sets refresh options for the data source (j_Source for file sources or j_DataQuery for database sources). Example 1: This example enables refresh on file open.
j_Source.setEnableRefreshOnFileOpen(true);

Example 2: This example illustrates how to enable refresh on file open when using JDBC data source.
// If using JDBC data source, do it on the query: j_DataQuery.setEnableRefreshOnFileOpen(true);

Example 3:

244

Programming e.Spreadsheet Reports

This example removes the data source from the file when it is saved.
j_Source.setEnableSourceRemovalBeforeSave(true);

Refreshing source data


Normally, data sources are set to refresh on file opening. For more information, see Setting data source refresh options earlier in this chapter.Setting data source refresh options. Under some circumstances a developer may need to set refresh to occur at a particular point in code or a user may want to see changes made to the data or data formatting immediately without closing and re-opening the file. Use one of the refresh methods from the DataSourceCollection or DataQueryCollection class or the Refresh or Refresh All command from the Data menu to refresh immediately.

Using the e.Spreadsheet Designer


To refresh the data source for the range the active cell is in and any other ranges connected to the same data source: 1 Choose DataRefresh. To refresh all data sources in the workbook: 1 Choose DataRefresh All.

Syntax
public void refresh() public void refresh(Source source) public void refresh(DataQuery query)

Parameters
Parameter source query Description the default or defined name of the data source to refresh, (j_DataSource in the example below). the data query to refresh.

Code Example
Example 1: This code example refreshes all data sources connected to the workbook.
// Refreshes all data from data sources connected to this JBook

Chapter 12, Connecting to external data

245

BMI.getDataSourceCollection().refresh();

Example 2: This code example refreshes data from the data source named j_DataSource. This refreshes data in all ranges in the worksheet that use j_DataSource.
// Refreshes data from the data source named j_DataSource BMI.getDataSourceCollection().refresh(j_DataSource);

Example 3: This code example refreshes data from the query j_DataQuery on the j_DataSource source. This will refresh all data in all ranges listening to j_DataQuery.
// refreshes data from the query j_DataQuery on the j_DataSource source j_DataSource.getDataQueryCollection().refresh(j_DataQuery);

Setting up a range
Creating a data range
Database or file data connected to e.Spreadsheet does not actually appear in a worksheet, nor is it manipulable by e.Spreadsheet until you create a data range to display the data. Note that the code example below uses both the DataSourceCollection interface factory() method and the DataRangeCollection interface factory() method. The DataRange class factory() method sets up the data range as described below. The DataSourceCollection interface factory() method constructs the data source. For more information about setting up a data source, see Creating a connection to a database data source earlier in this chapter.Creating a connection to a database data source. The DataRangeCollection class factory method sets up the data range by setting the name for the range and establishing the location of the first row and column to receive the data, setting the starting point (upper-left) for the entire range. The amount and layout of the data piped in from the database or file determines the eventual size of the range. The data range size may increase or decrease as the amount of data in the database or file changes, depending on the original database query and the type of formatting used.

Using the e.Spreadsheet Designer


1 Complete the steps required to connect to a database or file as listed in Creating a connection to a database data sourceCreating a connection to

246

Programming e.Spreadsheet Reports

a database data source or Creating a data source connection to a file earlier in this chapter.Creating a data source connection to a file. 2 Choose Next or DataCreate Data Range. Data Wizard - Data Range appears. 3 Type a name for the range in the Data Range Name text area. 4 Type the formula for a single cell (e.g., $A$1) indicating the upper-left cell from which to expand the range to fit all the query data. or 5 Choose New worksheet to have e.Spreadsheet enter all the data in a new worksheet starting at cell A1. 6 Choose Finish.

Syntax
public DataRangeCollection factory(java.lang.String name, int row, int column)

Parameters
Parameter name row column Description The symbolic name of the created data source. (test in the example code, below.) An integer representing the first row of the range. Zero-based index. An integer representing the first column of the range. Zerobased index.

Code Example
This code example establishes a database data source and sets up the corresponding data range.
// Gets data source from JBook. com.f1j.data.source.JDBC j_DataSource = (com.f1j.data.source.JDBC) BMI.getDataSourceCollection().factory("tests", com.f1j.data.DataSourceCollectionImpl.kJDBC); // Tells data source what the connection URL is. j_DataSource.setDatabase("jdbc:odbc:Sales"); // Tells data source what driver to use. j_DataSource.setDriverName("sun.jdbc.odbc.JdbcOdbcDriver");

Chapter 12, Connecting to external data

247

com.f1j.data.query.DataQuery j_DataQuery = j_DataSource.getDataQueryCollection().factory("testsQuery"); // Sets data handler to database mode. j_DataQuery.setDataHandlerType(com.f1j.data.handler.Handler .kJDBCResultSet); // Tells data source what the query is. ((com.f1j.data.query.DatabaseQuery)j_DataQuery) .setQuery("select * from Sales"); // Gets data range from JBook. com.f1j.data.DataRange d_DataRange = BMI.getDataRangeCollection(0).factory("test", 0, 0); // Gets an XSLT document. com.f1j.data.XSLTDocument XSLT = d_DataRange.getXSLTDocument(); // Specifies path to XSLT document doing the formatting. XSLT.setDocumentPath("c:\\shared\\DBSalesPeople.xsl"); // Tells data range that XSLT document will format. d_DataRange.setCellFormattingMode(com.f1j.data.DataRange .eCellFormatting_XSLT); // Connects data range to data source. BMI.getDataRangeCollection(0).setDataQuery(d_DataRange, j_DataQuery); // Refreshes the data range. BMI.getDataSourceCollection().refresh();

Setting data range properties


When importing data from a database, e.Spreadsheet provides options for:
s s s

importing all, part, or none of the database formatting along with the data, setting whether adjacent formulas fill down how data is replaced in the worksheet range.

You can also do this by assigning an XSL stylesheet to the data range. Using an XSL stylesheet provides much richer formatting options.

248

Programming e.Spreadsheet Reports

Using the e.Spreadsheet Designer


1 Complete the steps required to connect to a database or file as listed in Creating a connection to a database data sourceCreating a connection to a database data source or Creating a data source connection to a file earlier in this chapter.Creating a data source connection to a file. 2 Choose DataData Manager from the main menu. Data Manager appears. 3 Select an existing query from a database or file connection. 4 Choose Add Range. Data Wizard - Data Range appears. 5 Change the data range name in the Data Range Name window or leave the default name assigned by e.Spreadsheet. 6 Choose whether to display the data in the current sheet or in a new worksheet and choose Next. 7 Select the desired formatting options from the Formatting area to establish whether to include field names, row numbers or automatically adjust column width. 8 Also within the Formatting area, check Fill down formulas to enable the fill down formulas feature. This feature copies a formula in the topmost row of the column to the immediate right of the data range down into all the cells in that column for the length of the range. This process continues for every succesive column contiguous with the data range that contains a formula until a column with no formula to copy down is found. 9 Select the desired formatting options from the Cell Formatting area to establish whether to use XSLT formatting, use XML attributes, preserve the current cell formatting, replicate the formatting of the first row in the database, or clear all cell formatting. 10 Select the desired option to establish how the data range changes on refresh: add and delete cells, add and delete rows, or overwrite cells. 11 Choose Advanced to open Debug Data Range. In Debug Data Range, you:
s

indicate a path for outputting a file containing the data source XML, the XML sent to the XSLT processor indicate whether to save the file immediately or on refresh

12 Choose OK to return to the Data Wizard dialog and Finish to save the settings.

Syntax
public void setIncludeFieldNames(boolean include);

Chapter 12, Connecting to external data

249

Parameter
Parameter include Description boolean true/false. true = include field names from the data source in data imported to this range. Works only with data imported from a database that includes field names. Ignored when importing data with no field names.

Syntax
public void setIncludeRowNumbers(boolean include);

Parameter
Parameter include Description boolean true/false. true = include data source row numbers as the first column in the data range.

Syntax
public void setAdjustColWidth(boolean adjust);

Parameter
Parameter adjust Description boolean true/false. true = recalculate and adjust column width to match largest item in column on each refresh.

Syntax
public short getCellFormattingMode(); public void setCellFormattingMode(short mode);

Parameters
Parameter mode Description an integer or the constant representing one of the following cell formatting modes: Integer

250

Programming e.Spreadsheet Reports

Parameter

Description eCellFormatting_Clear clear existing database formatting keep existing database formatting use formatting from data range first row. use XSLT formatting

Integer 1

eCellFormatting_Preserve

eCellFormatting_ReplicateFirstRow

eCellFormatting_XSLT

Syntax
public String getName(); public void setName(String name)

Parameter
Parameter name Description the defined name to give the DataRange object. This is the same as the object name.

Syntax
public short getInsertMode(); public void setInsertMode(short mode);

Parameter
Parameter mode Description an insert mode constant:

Chapter 12, Connecting to external data

251

Parameter

Description eInsertDeleteCells Deletes all of the cells from the existing range (even if the existing range is larger than the one being inserted) and replaces them with new, unformattted cells containing the data from the data source. Replaces existing worksheet rows in the range with new, unformatted rows containing the data from the data source. Replaces exisiting worksheet data with data imported for the data source, leaving worksheet cell formatting as previously set by the setCellFormattingMode method.

eInsertClearRows

eOverwriteClearCells

Code Examples
Example 1: This code example sets the data range to include field names from the data source in the data range d_DataRange.
// Turns on field names. d_DataRange.setIncludeFieldNames(true);

Example 2: This code example sets the data range to include row numbers from the data source in the data range d_DataRange.
// Turns on row numbers. d_DataRange.setIncludeRowNumbers(true);

Example 3: This code example sets the columns in data range d_DataRange to automatically adjust to the size of the largest item in the column.
// Turns on automatic column width adjustment. d_DataRange.setAdjustColWidth(true);

Example 4: This code example sets the formula fill down feature to true. This feature causes a formula in the cell at the top of the column adjacent to and contiguous

252

Programming e.Spreadsheet Reports

with the data range to copy down below the formula for the length of the range. Formulas are copied down until no formula is found in the cell in the top row adjacent to the data range.
// Turns on fill-down formulas. d_DataRange.setFillDownFormulasAdjacentToRange(true);

Example 5: This code example calls the setInsertMode method with the constant eInsertDeleteCells, which overwrites all existing cells and replaces them with new, unformatted data from the source.
// Determines how data is replaced on refresh. d_DataRange.setInsertMode(eInsertDeleteCells);

Moving or deleting data ranges


Once you have named and created a data range, you can move it or delete it from the worksheet using the move and delete methods in the com.f1j.data.DataRangeCollection interface. Deleting a data range deletes the data connection, not the existing worksheet data or the source or query associated with the range.

Using the e.Spreadsheet Designer


To delete a data range: 1 Move the active cell in the worksheet to a cell within the data range to delete. 2 Select DataDelete Data Range. Or 1 Choose DataData Manager. 2 Select the data range to delete. 3 Choose Remove. To move a data range: 1 Select a cell within the data range to move. 2 Choose Data MenuEdit Data Range Options.... 3 Type the formula for the upper-leftmost cell of the new range location in the Existing worksheet: data entry area to move the data to a new location on the same worksheet.

Chapter 12, Connecting to external data

253

4 Select the New worksheet button to move the data to a range beginning with cell A1 on a new worksheet. 5 Choose Finish.

Syntax
public void delete(com.f1j.data.DataRange range)

Parameters
Parameter range Description the data range to delete.

Syntax
public void move(com.f1j.source.Source source, com.f1j.data.DataRange range, com.f1j.ss.Sheet sheet, int row int column) public void move(com.f1j.data.query.DataQuery query, com.f1j.data.DataRange range, com.f1j.ss.Sheet sheet, int row, int column)

Parameters
Parameter source query range sheet row column Description the name of the data source to move (e.g., j_Source). the name of the data query to move (e.g., j_DataQuery). the data range to move. the sheet to contain the target range (may be same as current sheet). the first row of the target range. the first column of the target range.

Code Examples
Example 1:

254

Programming e.Spreadsheet Reports

This example moves the data range d_Range (linked to j_DataSource) to the 31st column and 31st row of the first worksheet in the workbook.
d_Range = jBook.getDataRangeCollection(0).getDataRange(0); jBook.getDataRangeCollection(0).move(j_DataSource, d_Range, jBook.getBook().getSheet(0), 30, 30);

Example 2: This code example deletes the data range named d_Range.
d_Range = jBook.getDataRangeCollection(0).getDataRange(0); jBook.getBook().getSheet(0).getDataRangeCollection().delete(d_Range);

Using XML and XSLT


Using XSLT, e.Spreadsheet transforms XML documents in otherwise incompatible formats or layouts into XML documents that it can import, format, and use.

Importing XML using XSLT


To import XML using an XSL stylesheet to implement the formatting, you first establish and connect the data source and data range as described in Creating a connection to a database data source earlier in this chapter, Creating a connection to a database data source, then: 1 set the data handler to use XML with the setDataHandler method, 2 connect the data range and data source using the setDataSource or setDataQuery method(s) from the DataRangeCollection class, 3 set the path to the XSLT document with the setDocumentPath method, and 4 set the cell formatting mode for the data range to XSLT using the setCellFormattingMode method.

Using the e.Spreadsheet Designer


1 Open the Data Wizard. 2 Select the data range of the data source you want to import. For more information, see Creating a connection to a database data source earlier in this chapter.Creating a connection to a database data source.

Chapter 12, Connecting to external data

255

3 Choose Edit. Data Wizard - Data Range appears. 4 Choose Next. 5 Select XSLT Document. 6 Select Use XSLT. 7 Choose Set. XSLT File Options appears. 8 Choose Browse to set the path to the XSL stylesheet, or select Document and enter the stylesheet directly in the text area under Document. 9 If you chose Browse, Open appears. 10 In Open, navigate to and select the XSL stylesheet. Choose Open. 11 In XSLT Options, remove the path information, leaving only the file name and choose OK. 12 In Data Wizard - Data Range Options, choose Finish.

Syntax
public void Source.setDataHandler(int dataType)

Or
public void DataQuery.setDataHandler(int dataType)

Parameters
Parameter dataType Description an integer or the parameter representing one of the following types of data to be handled in the data connection: kJDBCResultSet kDelimitedText kXML kPositionalText a JDBC result set. delimited text. XML data or a text file to format with an XSLT document. text delimited by position.

Syntax
public void setCellFormattingMode(short mode)

256

Programming e.Spreadsheet Reports

Parameters
Parameter mode Description an integer or the parameter representing one of the following cell formatting modes: eCellFormatting_Clear eCellFormatting_Preserve eCellFormatting_ReplicateFirstRow eCellFormatting_XSLT clears existing worksheet formatting keeps existing worksheet formatting uses formatting from first row of data range uses XSLT formatting

Code Example
// Initializes the data handler for an XML file. If JDBC, use // f_DataQuery.setDataHandlerType(com.f1j.data.handler.Handler.kXML) f_DataQuery.setDataHandlerType(com.f1j.data.handler.Handler.kXML); // Gets XSLT document to use for formatting. com.f1j.data.XSLTDocument XSLT = d_DataRange.getXSLTDocument(); // Sets XSLT file path. XSLT.setDocumentPath("c:\\shared\\SalesPeople.xsl"); // Tells data range that XSLT document will format. d_DataRange.setCellFormattingMode(com.f1j.data.DataRange .eCellFormatting_XSLT);

Creating XSL stylesheets to convert XML


To import XML data into e.Spreadsheet in a usable, formatted form, or to take advantage of the formatting and reporting features available using XSLT formatting, developers can create an XSL stylesheet that converts existing XML data to conform with e.Spreadsheet XML tags and attributes for data cells. Developers may use an existing stylesheet as a template or create one from scratch. The following table lists the elements and attributes For a table listing the XML tags output by e.Spreadsheet, see Converting an e.Spreadsheet range to XML in Chapter 15, Reading and writing data.Converting an e.Spreadsheet range to XML.

Chapter 12, Connecting to external data

257

e.Spreadsheet XML attributes


Attributes absolute-defined-name alignment-horizontal
2

Range

Row1 X

Cell X X

Values string ("Jan") string: "general", "left", "center", "right", "fill", "justify", or "across" string: "top", "center", or "bottom" pattern style number (1...13), where: 0 is eBorderNone 1 is eBorderThin 2 is eBorderMedium 3 is eBorder Dashed 4 is eBorderDotted 5 is eBorderThick 6 is eBorderDouble 7 is eBorderHair 8 is eBorderMedium Dash 9 is eBorderDashDot 10 is eBorderMedium DashDot 11 is eBorderDash DotDot 12 is eBorderMedium DashDotDot 13 is eBorderSlanted DashDot RGB value (0XFF0000 = red) RGB value RGB value RGB value number (1...13, see borderbottom) number (1...13, see borderbottom) number (1...13, see borderbottom)

alignment-vertical border-bottom

X X

border-color-bottom border-color-left border-color-right border-color-top border-left border-right border-top

X X X X X X X

258

Programming e.Spreadsheet Reports

Attributes (continued) collapsed (for outlining) defined-name3 In the <cell> tag, these references are relative row/absolute column ($C1:$C14). To get absolute row/ absolute column defined names, use the absolute-defined-name attribute. font font-bold font-color font-italic font-size font-size-twips font-strikeout font-underline formula height height-centimeters height-inches height-twips hidden hlink hlinkType

Range

Row1 X X

Cell X X

Values (continued) boolean (true/false) string ("Jan")

X X X X X X X X X X X X X X X X X

X X X X X X X X X

string ("Arial") boolean (true/false) RGB value (0XFF0000 = red) boolean (true/false) number in points number in twips boolean (true/false) boolean (true/false) string ("Jan+Feb+Mar") number (12 points) number (.423 centimeters = 12 points) number (.167 inches = 12 points) number (240 twips = 12 points)

X X X

boolean (true/false) a hyperlink URL number 0...5 0 - Intra-document 1 - Absolute URL 2 - Relative URL 3 - Absolute file path 4 - Relative file path 5 - Network file path

Chapter 12, Connecting to external data

259

Attributes (continued) hlinkTooltip locked merge-horizontal

Range

Row1

Cell X

Values (continued) Displays tooltips for the hyperlink boolean (true/false) number indicating how many columns this cell spans degrees from -90 to 90, inclusive number 1...8 number for the pattern:

X X

orientation outline pattern

X X X

X X X

pattern-bg pattern-fg type value-format width

X X

X X X

RGB value (0XFF0000 = red) RGB value (0XFF0000 = red) general, text, number, or boolean string ("#,###.00;;;") number in character width (1/256th of the 0 character). For example, 256 equals 1 character. boolean (true/false)

X X

wrap

1. Formatting attributes in the <row> tag become default attributes of all the <cell> leaf nodes. 2. Defined names appearing in the <row> tag are defined as absolute row/ relative column (e.g., C$1:C$14). Defined names appearing in the <cell> tag are defined as relative row/absolute column (e.g., $C1:$C14). To get absolute row/absolute column defined names, use the absolute-defined-name attribute. 3. Defined names appearing in the <row> tag are defined as absolute row/ relative column (e.g., C$1:C$14). Defined names appearing in the <cell> tag are defined as relative row/absolute column (e.g., $C1:$C14). To get absolute row/absolute column defined names, use the absolute-defined-name attribute.

260

Programming e.Spreadsheet Reports

Setting conditional attributes


You can define a conditional element within a range, row, or cell element. If you set various conditions within different elements, the XSLT processor sets the range conditions, then the row conditions, and then the cell conditions. You can set up to three conditions for any cell. The following table contains the attributes required for each type of condition. <conditional> attributes Required attribute 1 type = "cell" Required attribute 2 Attribute 3 (for type="cell" only) Required attribute 4 Options: font font-color font-bold font-italic font-size font-size-twips font-strikeout font-underline pattern pattern-bg pattern-fg border-bottom border-left border-right border-top border-color-left border-color-right border-color-top

op = "between" value1="string1" value2 = "string2" op = "not between" The strings are the comparisons to the active cell (for example, between string1 and string2). op = "=" op = "!=" op ="<" op = ">" op = "<=" op = ">=" value = "string" The string is the comparison to the active cell.

type = "cell"

type = "formula"

formula = "expression" The expression is any valid e.Spreadsheet formula that evaluates to true or false.

Chapter 12, Connecting to external data

261

Example Syntax
This example applies the condition greater than 100. When the condition is met, the bold formatting is applied to the font.
<conditional type="cell" op=">" value="100" font-bold="true"/>

This example applies the condition between 100 and 500. When the condition is met, the font formatting changes to add italics.
<conditional type ="cell" op = "between" value1="100" value2="500" fontitalic="true"/>

This example applies the condition when the value in the cell is an even integer. When the condition is met, the font formatting changes to add underlining.
<conditional type = "formula" formula = "ISEVEN()" font-underline="true" />

Using e.Spreadsheet JDBC data grouping in XSL


The XML output by e.Spreadsheet includes <group> elements that developers can use to leverage SQL ORDER BY presorting. e.Spreadsheet adds <group> tags to data source XML if grouping options are set for the data connection and the SQL ORDER BY clause includes multiple items. e.Spreadsheet can add <group> tags on multiple levels. Developers can use the level attribute to take advantage of <group> tags in order to write more efficient XSL stylesheets. For more information, see Using the level attribute in XSLlater in this chapter.Using the level attribute in XSL. For more information about grouping, including example XML and XSLT, see Example 1: Stylesheet with grouped data in Chapter 3 in Designing e.Spreadsheet Reports. For more information about creating XSL stylesheets to format XML data in e.Spreadsheet data, see Creating XSL stylesheets to convert XML later in this chapter.Creating XSL stylesheets to convert XML.

Example syntax
All <group> tags include name, value, and level attributes. This example also includes label and table attributes returned by e.Spreadsheet by default.
<group name=city value=Boston label=city table=offices level=_1>

262

Programming e.Spreadsheet Reports

Using the level attribute in XSL


When e.Spreadsheet converts database data to data source XML, it automatically adds a level attribute within each <group> elements start tag. For top level <group> elements, e.Spreadsheet gives the level attribute the value _1 in the first element, _2 in the second, and so on for all the <group> elements at this level. e.Spreadsheet automatically assigns level attributes in any child <group> elements the values _1_1, _1_2, and so on for all the <group> elements at that top level. For each child level, e.Spreadsheet adds a value. For example, in RSML with three levels of groups, you have level attribute values like _1_1_1, _1_1_2, _2_1_3 and so on.

How to use the level attribute


The level attribute provides a convenient way to create a reference to all rows in a <group> element. For example, if you created a defined name that references the level attribute value _1_3, that defined name always refers to all rows within the <group> element with the level attribute _1_3 in the data source XML, even after new rows are added from the database data.

Using < and > symbols in an XSL stylesheet


Normally, placing a greater than or less than sign or bracket (> or <) or the code for these (&gt; or &lt;) in an XSL stylesheet causes the data on either side to be evaluated in the resulting file. To make the signs or code for the signs display as text, add the line of code shown below as the second line in the XSL stylesheet, immediately after <?XML version = "1.0"?>.

Code Example
<!DOCTYPE xsl:stylesheet [<!ENTITY lt "&#60;"><!ENTITY gt "&#63;">]>

Using a different XML parser or transformer


Default settings and behavior
By default, e.Spreadsheet uses Xerces as its DOM (Document Object Model) parser, and Xalan as the default XSLT processor (or transformer). The e.Spreadsheet program looks for the following files (javax.xml.parsers.SAXParserFactory, javax.xml.parsers.DocumentBuilderFactory, and javax.xml.transform.TransformerFactory) in the META-INF/services directory of the e.Spreadsheet JAR. Each of these files contain the class name of the parser or transformer to use during report execution.

Chapter 12, Connecting to external data

263

Changing e.Spreadsheets settings and behavior


Besides the default parser and processor, e.Spreadsheet works with two other parsers and one XSLT processor. Changing from the default parser or XSLT processor may disable XML validation and error checking. You can set e.Spreadsheet to use one of the different parsers or processors using any of the following options.

Option 1:
From the command prompt on the server machine.

To change the SAX parser to Crimson:


1 Add the following text to the Java command line for your application:
-Djavax.xml.parsers.SAXParserFactory = org.apache.crimson.jaxp.SAXParserFactoryImpl

2 Restart the application. This directs the application to use the Crimson parser found in the class path for the duration of the application.

To change the DOM parser to Crimson:


1 Add the following text to the Java command line for your application:
-Djavax.sml.parsers.DocumentBuilderFactory = org.apache.crimson.jaxp.DocumentBuilderFactoryImpl

2 Restart the application. This directs the application to use the Crimson parser found in the class path for the duration of the application.

To change the XSLT processor (transformer) to Saxon:


1 Add the following text to the Java command line for your application:
-Djavax.xml.transform.TransformerFactory = com.icl.saxon.TransformerFactoryImpl

2 Restart the application.

264

Programming e.Spreadsheet Reports

Option 2:
Modify the .../lib/jaxp.properties file. You can modify the by opening the jaxp.properties file in the JRE directory and adding the lines of code shown in Option 1 (without the -D command) . Modifying the jaxp.properties file changes the setting more permanently than changing the settings from the command prompt. The change applies to all applications that use the jaxp.properties file. Once the default JAR files Xerces and Xalan have been overridden, it is safe to delete them. The JAXP JAR file may not be safely deleted. JAXP 1.1 compliant parsers and transformers include: Xerces - 1.3.1 or later Crimson - the version that comes with JAXP 1.1 distribution Xalan - 2.0.1 or later Saxon 6.2.2 or later For more information about JAXP (Java API for XML Processing), see java.sun.com/xml/xml_jaxp.html. For more information about Java-compatible XML parsers and XSLT processors, see the Apache XML Project website at xml.apache.org and the Saxon home page at saxon.sourceforge.net/.

Chapter 12, Connecting to external data

265

266

Programming e.Spreadsheet Reports

Chapter

13
Chapter 13

Deploying on the Web

This chapter contains the following topics:


s s s s s s s s s

Creating a simple applet Embedding applets in a web page using one line of code Reducing applet and JavaBean size for use over the Internet Finding out which browsers are compatible with e.Spreadsheet Using VTS files Using write to save worksheets as HTML Using writeURL to save to a URL or output stream Using the writeURL servlet Loading worksheets with embedded applets

Creating a simple applet


This simple code example illustrates the minimal code needed to display a worksheet and access the API to place a text string in a worksheet cell. The HTML needed to add and display the applet on a web page is shown after the code example. For a more sophisticated example, see Using the sample application and applet in Chapter 1, Programming with e.Spreadsheet.Using the sample application and applet.

Chapter 13, Deploying on the Web

267

Code example
import java.awt.*; import com.f1j.swing.*; public class SimpleSwingApplet extends javax.swing.JApplet { public void init() { getContentPane().setLayout(null); setSize(500, 500); // Creates an instance of e.Spreadsheet and adds it to the JApplet. com.f1j.swing.JBook jbook1 = new com.f1j.swing.JBook(); jbook1.setSize(400, 400); getContentPane().add(jbook1); try { jbook1.setText(2, 0, "Welcome to e.Spreadsheet: " + "The Internet Spreadsheet"); } catch (com.f1j.util.F1Exception e) { } setVisible(true); } }

To test the code, compile and create an HTML page that accesses the .class file created when compiled, then access with a web browser.

Example HTML
The following HTML is an example of what is needed to display SimpleSwingApplet on a web page: This code must be run through Suns HTMLConverter program before viewing and can only be viewed using Suns Java 1.2.2 browser Plug-in. For more information about converting files for use with the Java Plug-in, see Finding out which browsers are compatible with e.Spreadsheet earlier in this chapterFinding out which browsers are compatible with e.Spreadsheet.
<HTML> <BODY> <APPLET CODE = "SimpleSwingApplet.class" ARCHIVE="f1j9swing.jar" NAME="f1" WIDTH=400 HEIGHT=400>

268

Programming e.Spreadsheet Reports

</APPLET> </BODY> </HTML>

Chapter 13, Deploying on the Web

269

Embedding applets in a web page using one line of code


e.Spreadsheet includes a fully functional worksheet applet developers can embed in a Web page or application with one line of HTML code. When embedding an e.Spreadsheet worksheet in a web page, place the required e.Spreadsheet JAR files on the server. Only one JAR file is required to view and serve live worksheets from a web server.

Code Example
The only JAR file required to view and serve live worksheets from a web server is f1j9swing.jar. This HTML code must be run through Suns HTMLConverter program before viewing and can only be viewed using Suns Java 1.2.2 browser Plug-in. For more information about converting files for use with the Java Plug-in, see Finding out which browsers are compatible with e.Spreadsheet later in this chapter.Finding out which browsers are compatible with e.Spreadsheet. To embed an applet in a Web page: 1 Write an HTML file that contains at least the following code. The contents of f1j9awt.jar must be un-jarred into the web servers classes directory.
<HTML> <HEAD> <TITLE> Live Worksheet Page </TITLE> </HEAD> <BODY> <APPLET CODE="com.f1j.swing.JBookApplet" WIDTH=550 HEIGHT=375></ APPLET> </BODY> </HTML>

2 If the applet is in a JAR file, specify the name of the JAR file by adding the ARCHIVE option to the APPLET CODE tag.
<APPLET CODE="com.f1j.swing.JBookApplet" ARCHIVE="SimpleJBook.jar" WIDTH=550 HEIGHT=375></APPLET>

3 If the applet is in a CAB file, specify the name of the CAB file by adding the CABBASE option to the APPLET CODE tag.

270

Programming e.Spreadsheet Reports

<APPLET CODE="com.f1j.swing.JBookApplet" CABBASE="SimpleJBook.cab" WIDTH=550 HEIGHT=375></APPLET>

Finding out which browsers are compatible with e.Spreadsheet


In order to use the Swing-based workbook, your browser must comply with Suns requirements for Swing. Currently, this is JVM 1.1.8 or JVM 1.2.2. Since most browsers do not support those JVMs natively, the Sun Java 1.2.2 browser Plug-in is also required. In order to run the Swing version within the Java Plug-in, you must convert all of your APPLET tags to OBJECT tags (Internet Explorer) or EMBED tags (Netscape). A Sun-provided converter, HTML Converter, will do this conversion automatically for you. You can download the Java Plug-in for your platform and Suns HTML Converter at http://java.sun.com. The AWT-based workbook will run as an applet with a minimum of Netscape Communicator 4.05 and Internet Explorer 4.01. Actuate recommends that users have the latest releases of Netscape Navigator or Microsoft Internet Explorer available. As a minimum, upgrade to Netscape Navigator Version 4.6.1 or Internet Explorer Version 4.72.x.

Using VTS files


e.Spreadsheet creates, reads, and saves worksheets in its native VTS file format. Any application or applet created with e.Spreadsheet Files can also created, read, and save worksheets in the VTS format. The VTS file format is a compressed file format optimized for portability and network transmission. Using VTS files in your application significantly reduces download and transmission times when sharing data via e.Spreadsheet workbooks.

Chapter 13, Deploying on the Web

271

Using write to save worksheets as HTML


Use the write and setFlags methods of the HTMLWriter utility class to save an entire worksheet or a selected area of the worksheet with or without formatting as an HTML table. Many of the format attributes applied to a worksheet can be saved with an exported HTML table. By default, all exportable format attributes are exported. Choose the specific attributes to save using the setFlags method. The setFlags method Parameters table lists the tags of exportable formats. Use the getFlags method to get the current worksheet or range attribute settings.

Using the e.Spreadsheet Designer


1 Choose FileSave As. 2 Select Files of Type and scroll to the bottom of the list. 3 Select HTML or HTML Data Only. The Save AsHTML option saves the worksheet with all HTML formatting options intact. The Save AsHTML Data Only option saves the worksheet with no formatting. 4 Choose Save.

Syntax
public void write(Book book, int isheet1, int irow1, int icol1, int isheet2, int irow2, int icol2, java.io.Writer writer)

Parameters
Parameter book sheet1 row1 col1 Description The Book containing the range of data to output. The starting sheet to output from. The starting row of the range to output from. The starting column of the range to output from.

272

Programming e.Spreadsheet Reports

Parameter sheet2 row2 col2 writer

Description (continued) The ending sheet to output from. The ending row to output from. The ending column to output from. An output stream to output the range to.

Syntax
public void setFlags(int flags)

Parameters
Parameter int flags Controls Sheet number Combinations of these flags. NONE VALUE_FORMATS BORDER_TAG HEIGHT_TAG WIDTH_TAG BGCOLOR_TAG FONT_TAG COLSPAN_TAG ALIGN_TAG VALIGN_TAG ALL No tags or value formatting. Outputs cell values with value formats. Turns on table border. Uses the HTML HEIGHT tag to set row heights. Uses the HTML WIDTH tag to set the column widths. Uses the HTML BGCOLOR tag to set the background color of the cells. Uses the HTML FONT tag to set the font attributes. Uses the HTML COLSPAN tag to display data that overlaps cells Uses the HTML ALIGN tag to set the horizontal alignment. Uses the HTML VALIGN tag to set the vertical alignment. (Default) Applies all flags except BORDER_TAG. Flag Description

Chapter 13, Deploying on the Web

273

Code Example
public void htmlToFile(){ com.f1j.ss.HTMLWriter htmlWriter = new com.f1j.ss.HTMLWriter(); try { // Data in 3 sheets to write to the file. jbook1.insertSheets(0, 2); jbook1.setText(2, 3, "test1"); jbook1.setText(1, 2, 3, "test2"); jbook1.setText(2, 2, 3, "test3"); // Sets the selection area on each sheet to write to the file. jbook1.setSelection("A1:D3"); // Sets up the path to output the file String currentDir = System.getProperty("user.dir"); String fileSeparator = System.getProperty("file.separator"); String filename = currentDir + fileSeparator + "testHTML.html"; java.io.FileWriter writer = new java.io.FileWriter(filename); // Set all of the flag properties of the file to output htmlWriter.setFlags(htmlWriter.ALL); // Write to HTML format using the selected range on all sheets int i = jbook1.getNumSheets(); com.f1j.ss.RangeRef range = Jbook1.getSelection(0); htmlWriter.write(jbook1.getBook(), 0, range.getRow1(), range.getCol1(), i-1, range.getRow2(), range.getCol2(), writer); // Or write the Book to HTML format with spaces between each sheet. htmlWriter.write(Jbook1.getBook(), writer); writer.close(); } catch (com.f1j.util.F1Exception e1) { } catch (java.io.IOException e2){ } }

Using writeURL to save to a URL or output stream


There are nine different writeURL methods used with e.Spreadsheet. All nine methods save a workbook or a range of data to a specified URL or output

274

Programming e.Spreadsheet Reports

stream and require that you have a servlet running on a web server to accept the post generated. The different methods allow for various sets of parameters as outlined below. Before calling any of writeURL methods from the com.f1j.ss.Book interface-the first three writeURL methods listed below--call one of the read methods to load a spreadsheet into the workbook or call the book.initBook method.

Method 1 Syntax
public boolean writeURL(Sheet sheet, java.lang.String host, int port, java.lang.String servlet, java.lang.String file, WriteParams wp)

Parameters
Parameter sheet host port servlet file wp Description The sheet to write. Web servers host address. Web server port, -1 for default (e.g. 80 on http). Path of servlet accepting the post. Relative path of file. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Code Example
java.net.URL Url = new java.net.URL("www.yoursite.com"); String strHost = Url.getHost(); Int intPort = Url.getPort(); String strServlet = new String("/servlets/f1j_writeurl"); String strFile = new String("TestFile.vts"); Book.writeURL(sheet, strHost, intPort, strServlet, strFile, new com.f1j.ss.WriteParams(Book.eFileFormulaOne3));

Chapter 13, Deploying on the Web

275

Method 2 Syntax
public boolean writeURL(Sheet sheet, java.lang.String logicalSpec, WriteParams wp)

Parameters
Parameter sheet logicalSpec wp Description The sheet to write The string containing the URL address A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Returns: true false If the file is completely written. If the specified file format does not support all the features used by this workbook.

Code Example
com.f1j.ss.Sheet sheet = Book.getSheet(0); String strLspec = new String("www.yoursite/TestFile.vts"); Book.writeURL(sheet, strLspec, new com.f1j.ss.WriteParams(Book.eFileFormulaOne3));

Method 3 Syntax
public boolean writeURL(Sheet sheet, java.net.URL URL, WriteParams wp)

276

Programming e.Spreadsheet Reports

Parameters
Parameter sheet URL wp Description The sheet to write. The Uniform Resource Locator. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams. If the file is completely written. If the specified file format does not support all the features used by this workbook.

Returns: true false

Code Example
URL Url = java.net.URL("www.yoursite.com/servlets/ f1j_writeurl?file=TestFile.vts"); Book.writeURL(sheet, Url, new com.f1j.ss.WriteParams(Book.eFileFormulaOne3));

Method 4 Syntax
public void writeURL(java.lang.String logicalSpec, int sheet1, int row1, int col1, int sheet2, int row2, int col2, WriteParams wp)

Parameters
Parameter logicalSpec sheet1 row1 col1 Description The string containing the URL address. Sheet number. Row number. Column number.

Chapter 13, Deploying on the Web

277

Parameter sheet2 row2 col2 wp

Description (continued) Sheet number. Row number. Column number. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Code Example
java.lang.String logicalSpec = new String("www.yoursite.com/TestFile.vts"); jbook1.writeURL(logicalSpec, 0, 0, 0, 0, 15, 15, new com.f1j.ss.WriteParams(Jbook1.eFileFormulaOne3));

Method 5 Syntax
Public void writeURL(java.lang.String host, int port, java.lang.String servlet, java.lang.String file, int sheet1, int row1, int col1, int sheet2, int row2, int col2, WriteParams wp)

Parameters
Parameter host port servlet file sheet1 row1 Description Web servers host address. Web server port, -1 for default (i.e. 80 on http). Path of servlet accepting the post. Relative path of file. Sheet number. Row number.

278

Programming e.Spreadsheet Reports

Parameter col1 sheet2 row2 col2 wp

Description (continued) Column number. Sheet number. Row number. Column number. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Code Example
java.net.URL Url = new java.net.URL(www.yoursite.com); String strHost = Url.getHost(); Int intPort = Url.getPort(); String strServlet = new String("/servlets/f1j_writeurl"); String strFile = new String("TestFile.vts"); jBook1.writeURL(strHost, intPort, strServlet, strFile, 0, 0, 0, 1, 15, 15, new com.f1j.ss.WriteParams(jBook1.eFileFormulaOne3));

Method 6 Syntax
public void writeURL(java.lang.String host, int port, java.lang.String servlet, java.lang.String file, WriteParams wp)

Parameters
Parameter host port servlet file wp Description Web servers host address. 1 for default (i.e. 80 on http). Path of servlet accepting the post. Relative path of file. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Chapter 13, Deploying on the Web

279

Code Example
java.net.URL Url = new java.net.URL("www.yoursite.com"); String strHost = Url.getHost(); int intPort = Url.getPort(); String strServlet = new String("/servlets/f1j_writeurl"); String strFile = new String("TestFile.vts"); jBook1.writeURL(strHost, intPort, strServlet, strFile, new com.f1j.ss.WriteParams(jBook1.eFileFormulaOne3));

Method 7 Syntax
public void writeURL(java.lang.String logicalSpec, WriteParams wp)

Parameters
Parameter logicalSpec wp Description The string containing the URL address. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Code Example
String strLspec = new String("www.yoursite.com/servlets/f1j_writeurl"); Book.writeURL(strLspec, new com.f1j.ss.WriteParams(Book.eFileFormulaOne3));

Method 8 Syntax
public void writeURL(java.net.URL URL, int sheet1, int row1, int col1, int sheet2, int row2, int col2, WriteParams wp)

280

Programming e.Spreadsheet Reports

Parameters
Parameter URL sheet1 row1 col1 sheet2 row2 col2 wp Description The URL. Sheet number. Row number. Column number. Sheet number. Row number. Column number. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Code Example
java.net.URL Url = new java.net.URL("www.yoursite.com/servlets/f1j_writeurl ?file=TestFile.vts"); jbook1.writeURL(Url, 0, 0, 0, 1, 15, 15, new com.f1j.ss.WriteParams(jbook1.eFileFormulaOne3));

Method 9 Syntax
public void writeURL(java.net.URL URL, WriteParams wp)

Parameters
Parameter URL wp Description The URL. A WriteParams object indicating how e.Spreadsheet will write the file. For more information, see Using ReadParams and WriteParams in Chapter 15, Reading and writing data.Using ReadParams and WriteParams.

Code Example
java.net.URL Url = new java.net.URL("www.yoursite.com/servlets/f1j_writeurl

Chapter 13, Deploying on the Web

281

?file=TestFile.vts"); jbook1.writeURL(Url, new com.f1j.ss.WriteParams(jbook1.eFileFormulaOne3));

The e.Spreadsheet distribution media contains a servlet f1j_writeurl that you can use. For more information see the f1j_writeurl.readme file in the install_dir/servlets directory for further details.

Using the writeURL servlet


To use the writeURL method, install the servlet f1j_writeurl.class file found in the install_dir/servlets directory into your web servers servlet directory. This servlet is used in conjunction with e.Spreadsheets writeURL method. The example servlet is a sample multi-threaded servlet that takes input from a post and writes it to a specified file. After the results are written to the file, the servlet returns a 200.

Code Example
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /* * * Status Codes Returned: * 200 ok * * Error Codes Returned: (As text in the http results entity body) * 0 ok * 1 error writing file * 2 missing parameter * * Init Parameters: * rootPath root directory path to place files * * Query Parameters: * file relative path to store file * */

282

Programming e.Spreadsheet Reports

public class f1j_writeurl extends javax.servlet.http.HttpServlet { private final short WRITEURL_Ok = 0; private final short WRITEURL_ErrorWritingFile = 1; private final short WRITEURL_MissingParameter = 2; private final short MAXBUFFER = 4096; private String rootPath; public void init(javax.servlet.ServletConfig config) throws javax.servlet.ServletException { super.init(config); rootPath = getInitParameter("rootPath"); // rootPath if (rootPath != null) { if (!rootPath.endsWith(java.io.File.separator)) { rootPath += java.io.File.separatorChar; } } else { // rootPath is a required parameter. Enumeration initParams = getInitParameterNames(); System.err.println("The init parameters were: "); while (initParams.hasMoreElements()) { System.err.println(initParams.nextElement()); } System.err.println("Should have seen one parameter name"); throw new UnavailableException (this, "Must give a rootPath, indicating location to store files."); } } // init public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Hashtable queryParameters = javax.servlet.http.HttpUtils. parseQueryString(request.getQueryString()); String fileParameters[] = (String[])queryParameters.get("file"); PrintWriter toClient = response.getWriter(); short result = WRITEURL_Ok; response.setContentType("text/plain"); if (fileParameters != null) { try { writeFile(rootPath + fileParameters[0], request.getInputStream());

Chapter 13, Deploying on the Web

283

} catch (IOException e) { result = WRITEURL_ErrorWritingFile; } } else { result = WRITEURL_MissingParameter; } toClient.println(result); toClient.close(); } // doPost // Writes a file using data from input stream. private void writeFile(String fileName, java.io.InputStream input) throws java.io.IOException { java.io.FileOutputStream output = new java.io.FileOutputStream(fileName); try { byte buffer[] = new byte[MAXBUFFER]; int bytesRead; while (true) { bytesRead = input.read(buffer); if (bytesRead < 0) break; if (bytesRead > 0) output.write(buffer, 0, bytesRead); } } finally { if (output != null) output.close(); } } // writeFile } // writeURL

Loading worksheets with embedded applets


To load a e.Spreadsheet VTS file in an embedded applet, you must add the PARAM tag within the APPLET tag in the HTML code: In the code example, the VALUE option is the name of the worksheet you want to load. The

284

Programming e.Spreadsheet Reports

PARAM NAME attribute has three settings . The settings are described in the following table.

Param Name group

Description Calls the setGroup method, setting the group name for the workbook attached to the current view. This allows external references between workbooks in the same group. Calls the attach method and attaches the current view to the specified views workbook. This allows multiple workbooks to display data from the same view. Workbooks must belong to the same group before they can be attached by name. Calls the readURL method and reads a workbook from the specified web page.

workbookname

workbook

Code Example
<APPLET CODE="com.f1j.swing.JBookApplet.class" WIDTH=550 HEIGHT=375> <PARAM NAME="workbook" VALUE="spreadsheet.vts"> </APPLET>

Chapter 13, Deploying on the Web

285

286

Programming e.Spreadsheet Reports

Chapter

14
Chapter 14

Deploying on a server

This chapter contains the following topics:


s s s s s s

Creating a servlet Creating servlets and applications with no GUI overhead Using the BookModel object Deploying e.Spreadsheet within other application servers Using e.Spreadsheet within Java Server Pages (JSP) Analyzing user input from and returning HTML formatted data to the browser Accessing the API using JavaScript

Chapter 14, Deploying on a server

287

Creating a servlet
The following sample code is a servlet that creates a framed document. Below is the code for the frameset, its two pages, and the servlet that powers the example. The comments within the code sections provide more information on how this is put together.

Code Example
This is the code for the frameset, amortization.htm:
<HTML> <HEAD> <TITLE>Southcreek Realty Co. - Instant Amortization</TITLE> </HEAD> <frameset cols=200,* frameborder="0" framespacing="0" border="0"> <frame src="loanservlet.htm" name="left" scrolling=no noresize MARGINWIDTH=0 MARGINHEIGHT=0> <frame src="amorstart.htm" name="right" scrolling=yes noresize MARGINWIDTH=0 MARGINHEIGHT=0> </frameset> </HTML>

This is the code for the right page of the frameset, amorstart.htm:
<HTML> <HEAD> <TITLE>Southcreek Realty Co. - Instant Amortization</TITLE> </HEAD> <BODY> <CENTER> <TABLE WIDTH=400> <TR> <TD WIDTH=400 VALIGN=TOP> <CENTER><IMG SRC="topbannr.gif" WIDTH=400 HEIGHT=45 BORDER=0 ALT="Southcreek Realty"></CENTER><BR> <BR> <FONT SIZE="-1" FACE="ARIAL, HELVETICA">

288

Programming e.Spreadsheet Reports

<P>Welcome to the Southcreek Realty Instant Amortization feature of our Web site. Please fill out the information at left to see your proposed amortization schedule. </P> </TD></TR> </TABLE> </CENTER> </BODY> </HTML>

This is the code for the left page of the frameset, loanservlet.htm:
<HTML> <HEAD> <TITLE>Southcreek Realty Company - Amortization Calculator</TITLE> </HEAD> <BODY BGCOLOR="#5F8090"> <!--Make a path to the servlet in the ACTION statement to process the form input data when submitted--> <FORM METHOD=GET ACTION="http://www.f1j.com/servlet/LoanServlet" TARGET="right"> <TABLE WIDTH=220> <TR> <TD WIDTH=220 ALIGN=MIDDLE COLSPAN=2> <IMG SRC="house.gif" WIDTH=150 HEIGHT=150><BR> <BR></TD> </TR> <!--Ask the price of the house; name it price--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>List Price: </B></FONT></ TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="price" TYPE="TEXT" SIZE="7"></TD></TR> <!--Ask for the percent of the price being put down; name it down--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Money Down %:</B></ FONT></TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="down" TYPE="TEXT" SIZE="7"></TD></TR>

Chapter 14, Deploying on a server

289

<!--Ask for the percent of the closing cost; name it closing--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Closing %:</B></FONT></ TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="closing" TYPE="TEXT" SIZE="7"></TD></TR> <!--Ask for a 15 or 30 year term on the loan, name it years--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Years:</B></FONT></TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><SELECT NAME="years"> <OPTION SELECTED>15</OPTION> <OPTION>30</OPTION> </SELECT></TD></TR> <!--Ask for the rate of the loan, name it interest--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Interest:</B></FONT></ TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="interest" TYPE="TEXT" VALUE="7.0" SIZE="3"></TD></TR> <TR> <TD WIDTH=220 COLSPAN=2 ALIGN=MIDDLE><BR> <BR><INPUT TYPE="Submit" value="Calculate"></TD></TR> </TABLE> </FORM> </BODY> </HTML>

This is the code for LoanServlet.class. This servlet is referenced as the ACTION in the form on loanservlet.htm.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import com.f1j.swing.*; public class LoanServlet extends HttpServlet { com.f1j.swing.JBook workbook = new com.f1j.swing.JBook(); boolean needsReadWorkbook = true; com.f1j.ss.HTMLWriter htmlWriter = new com.f1j.ss.HTMLWriter(); public void doGet(HttpServletRequest req, HttpServletResponse res)

290

Programming e.Spreadsheet Reports

throws ServletException, IOException { res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); out.println("<html>"); out.println("<head><title>Southcreek Realty Co. - " + "Instant Amortization</title></head>"); out.println("<body>"); out.println("<BR> <BR> <BR>"); out.println("<CENTER>" + "<IMG SRC=http://www.f1j.com/demos/topbannr.gif" + "WIDTH=400 HEIGHT=45 BORDER=0" + "ALT=Southcreek Realty><CENTER><BR> <BR>"); out.println("<CENTER>"); out.println("<font point-size=8>"); out.println("<table><tr><td valign=top>"); // Get the parameters from the form String priceParam = req.getParameter("price"); String downParam = req.getParameter("down"); String closingParam = req.getParameter("closing"); String yearsParam = req.getParameter("years"); String interestParam = req.getParameter("interest"); // Make sure the parameters have data in them if ((priceParam != null) && (downParam != null) && (closingParam != null) && (yearsParam != null)) { java.io.Writer writer = new java.io.OutputStreamWriter(out); try { // Lock the workbook to prevent another thread from conflicting with // this request. workbook.getBook().getLock(); try { if (needsReadWorkbook) { // Read in the workbook mortgage.vts from the server. This // workbook must be in the directory from which the web server // was run for this to work. htmlWriter.setFlags(htmlWriter.ALIGN_TAG | htmlWriter.VALUE_FORMATS | htmlWriter.BORDER_TAG); workbook.read("servlets/mortgage.vts", new com.f1j.ss.ReadParams()); needsReadWorkbook = false; } // Enter the data into the workbook workbook.setEntry(1, 2, priceParam); if (!downParam.endsWith("%"))

Chapter 14, Deploying on a server

291

downParam = downParam + "%"; workbook.setEntry(2, 1, downParam); if (!closingParam.endsWith("%")) closingParam = closingParam + "%"; workbook.setEntry(4, 1, closingParam); workbook.setEntry(6, 2, yearsParam); workbook.setEntry(10, 3, interestParam); // Output the first table. htmlWriter.write(workbook.getBook(), 0, 0, 0, 0, 19, 2, writer); // Output the amortization table. writer.write("</td><td valign=top>"); htmlWriter.write(workbook.getBook(), 0, 31, 5, 0, yearsParam.equals("15")?46:61, 9, writer); } finally { // Release the lock or no other thread can use the object. workbook.releaseLock(); } } catch (java.io.IOException e) { // Got an exception. Report it on the HTML page. writer.write("Got exception e=" + e.getMessage()); } catch (com.f1j.util.F1Exception e) { // Got an exception. Report it on the HTML page. writer.write("Got exception e=" + e.getMessage()); } } out.println("</td></tr></table>"); out.println("</CENTER>"); out.println("</body></html>"); } public String getServletInfo() { return "Southcreek Realty Co. - Instant Amortization"; } }

Creating servlets and applications with no GUI overhead


The BookModel interface allows all of e.Spreadsheet to be deployed on a server with none of the overhead of a GUI. Servlets and server applications

292

Programming e.Spreadsheet Reports

built with previous versions of e.Spreadsheet may be converted to deploy without a GUI or any of the overhead associated with a GUI by replacing the com.f1j.swing.JBook class and methods with the com.f1j.ss.BookModelImpl class and methods.

Code Example
This code example creates a GUI-less servlet that creates a BookModelImpl that reads in an e.Spreadsheet VTS file and writes out a file in Excel 8/9 Office 97/2000 format.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ExcelServletJDBC extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Tells the browser we are sending a excel image response.setContentType("application/vnd.ms-excel"); // Gets the responsess output stream for this request ServletOutputStream out = response.getOutputStream() ; // Creates a new e.Spreadsheet BookModelImpl com.f1j.ss.BookModelImpl BMI = new com.f1j.ss.BookModelImpl(); BMI.getLock(); try { // Reads in the e.Spreadsheet file used as a template for this report BMI.read("c:\shared_documents\template.vts", new com.f1j.ss.ReadParams()); // Forces a recalculation since we change the contents of the book BMI.recalc(); // Writes the information out to a Microsoft Excel 97/2000 file BMI.write(out, new com.f1j.ss.WriteParams(BMI.eFileExcel97); // Closes the outputstream to flush the buffer out.close(); } catch(Throwable e) { System.out.println(e.getMessage()); }

Chapter 14, Deploying on a server

293

finally { BMI.releaseLock(); } } // doGet } // ExcelServlet

Using the BookModel object


The e.Spreadsheet API includes a BookModel object that can participate in a MVC (Model-View-Controller) pattern. The BookModel object can also be used in applications that do not require a graphical user interface. The BookModel object has most of the functionality of the e.Spreadsheet JBook object.

Code Example
com.f1j.ss.BookModel book1 = new com.f1j.ss.BookModel(); //Initialization book1.initWorkbook();

Using e.Spreadsheet within Java Server Pages (JSP)


This example takes advantage of the Java Web Servers page compilation feature allowing you to embed Java code in an HTML page within <java> </java> tags. The example creates a .jhtml file that asks the user to input a formula. The formula, passed from the HTML form to a workbook, is created on the fly, calculated by and returned to an HTML page by e.Spreadsheet. The code comments further explain how this works. For more information about using e.Spreadsheet with JSP, see Installing the JSP Charting API

Code Example
This code example also works with JSP; however, the <java> tag must be replaced with the JSP equivalent tag.
<HTML> <java type=class>

294

Programming e.Spreadsheet Reports

/* * Create a single worksheet object for the servlet. This worksheet is used to * do the calculation when a request comes in. */ com.f1j.swing.JBook workbook = new com.f1j.swing.JBook(); </java> <HEAD> <TITLE>e.Spreadsheet: Server/Calculate Demo</TITLE> </HEAD> <BODY> <CENTER> <!--Build a table to hold the instructions for the user--> <TABLE WIDTH=400> <TR> <TD WIDTH=400 VALIGN=TOP ALIGN=MIDDLE> <H4>e.Spreadsheet<BR>Server/Calculate Demo</H4> </TD> </TR> <TR> <TD WIDTH=400 VALIGN=TOP> <FONT SIZE="-1" FACE="ARIAL, HELVETICA"> <P>This demo displays the calculational uses of e.Spreadsheet. This operation requires no download--to complete the test calculation, enter a value in the text box below and click the button. The results will be displayed below.</P> <CENTER> <P><B>Enter your formula here.</B></P> <!--Build an HTML form to capture the users formula--> <!--Note the ACTION statement, which points to this page where the Java code is--> <FORM METHOD=GET ACTION="calculate.jhtml"> <!--The name of the value of the formula to pass to e.Spreadsheet is theFormula--> <INPUT NAME="theFormula" TYPE="TEXT" Size="40"><BR> <FONT SIZE="-2" FACE="ARIAL, HELVETICA">For example: pi() * 2</FONT> <BR> <BR> <INPUT TYPE="Submit" value="Calculate"> </FORM>

Chapter 14, Deploying on a server

295

<FONT SIZE="-1" FACE="ARIAL, HELVETICA"> <P><B>The calculations results are:</B></P> <!--This is where the formula will be calculated and its results displayed--> <JAVA> /* * Suns Java Web Server allows embedded Java code in an HTML page * inside of <JAVA>...</JAVA> tags. * * This simple Java code will lock the workbook, enter a formula, * get the result of the formula and return it on an HTML page. */ String result = ""; // Output an empty string by default // Catch any exceptions. try { // Get the URL parameter named "theFormula" if there is one. String theFormula = request.getParameter("theFormula"); if (theFormula != null) { /* * Lock the workbook so that another request on another thread will * not conflict with this request. */ workbook.getLock(); try { /* * Enter the formula into the cell at A1. An exception will * be thrown if the formula is not properly formed. */ workbook.setFormula(0, 0, theFormula); /* * Get the result of the formula. e.Spreadsheet automatically * recalculates the formula for us. */ result = workbook.getText(0, 0); } finally { /* * Release the lock. This must happen or no other thread * will be able to use the object. */

296

Programming e.Spreadsheet Reports

workbook.releaseLock(); } } } catch (Throwable e) { // Got an exception. Report it on the HTML page. result = "Got exception e=" + e.getMessage(); } // Output the string. out.println(result); </JAVA> </TD></TR> </TABLE> </FONT> </CENTER> </BODY> </HTML>

Analyzing user input from and returning HTML formatted data to the browser
In the code example below, data is calculated via an HTML form. This form invokes a .jhtml page on the web server and passes the form data. The .jhtml page loads a predefined spreadsheet that transfers the form data to the spreadsheet, recalculates, and then writes the spreadsheet back to the browser using the HTMLWriter class. This demo is a framed document. Below are the listings for the frameset, its two pages, and the .jhtml page that powers the demo. See the comments within the code for more information on how this is put together.

Code Example
This is the code for the frameset, amortization.htm:
<HTML> <HEAD> <TITLE>Southcreek Realty Co. - Instant Amortization</TITLE> </HEAD> <frameset cols=200,* frameborder="0" framespacing="0" border="0">

Chapter 14, Deploying on a server

297

<frame src="loan.htm" name="left" scrolling=no noresize MARGINWIDTH=0 MARGINHEIGHT=0> <frame src="amorstart.htm" name="right" scrolling=yes noresize MARGINWIDTH=0 MARGINHEIGHT=0> </frameset> </HTML>

This is the code for the right page of the frameset, amorstart.htm:
<HTML> <HEAD> <TITLE>Southcreek Realty Co. - Instant Amortization </TITLE> </HEAD> <BODY> <BR> <BR> <BR> <CENTER> <TABLE WIDTH=400> <TR> <TD WIDTH=400 VALIGN=TOP> <CENTER><IMG SRC="topbannr.gif" WIDTH=400 HEIGHT=45 BORDER=0 ALT="Southcreek Realty"></CENTER><BR> <BR> <FONT SIZE="-1" FACE="ARIAL, HELVETICA"> <P>Welcome to the Southcreek Realty Instant Amortization feature of our Web site. Please fill out the information at left to see your proposed amortization schedule.</P> </TD></TR> </TABLE> </CENTER> </BODY> </HTML> This is the code for the left page of the frameset, loan.htm: <HTML> <HEAD> <TITLE>Southcreek Realty Company - Amortization Calculator</TITLE> </HEAD> <BODY BGCOLOR="#5F8090">

298

Programming e.Spreadsheet Reports

<!--Call loan.jhtml in the ACTION statement to process the form input data when submitted--> <FORM METHOD=GET ACTION="loan.jhtml" TARGET="right"> <TABLE WIDTH=220> <TR> <TD WIDTH=220 ALIGN=MIDDLE COLSPAN=2> <IMG SRC="house.gif" WIDTH=150 HEIGHT=150><BR> <BR></TD> </TR> <!--Ask the price of the house; name it price--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>List Price: </B></FONT></ TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="price" TYPE="TEXT" SIZE="7"></TD></TR> <!--Ask for the percent of the price being put down; name it down--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Money Down %:</B></ FONT></TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="down" TYPE="TEXT" SIZE="7"></TD></TR> <!--Ask for the percent of the closing cost; name it closing--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Closing %:</B></FONT></ TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="closing" TYPE="TEXT" SIZE="7"></TD></TR> <!--Ask for a 15 or 30 year term on the loan, name it years--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Years:</B></FONT></TD> <TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><SELECT NAME="years"> <OPTION SELECTED>15</OPTION> <OPTION>30</OPTION> </SELECT></TD></TR> <!--Ask for the rate of the loan, name it interest--> <TR> <TD WIDTH=120 VALIGN=MIDDLE ALIGN=RIGHT><FONT SIZE="-1" FACE="ARIAL, HELVETICA" COLOR="#FFFFF7"><B>Interest:</B></FONT></ TD>

Chapter 14, Deploying on a server

299

<TD WIDTH=100 VALIGN=TOP ALIGN=LEFT><INPUT NAME="interest" TYPE="TEXT" VALUE="7.0" SIZE="3"></TD></TR> <TR> <TD WIDTH=220 COLSPAN=2 ALIGN=MIDDLE><BR> <BR><INPUT TYPE="Submit" value="Calculate"></TD></TR> </TABLE> </FORM> </BODY> </HTML>

This is the code for loan.jhtml. This page is referenced as the ACTION in the form on amorstart.htm:
<HTML> <java type=class> /* * Creates a single worksheet object for the servlet. * This worksheet is used to do the calculation when * a request comes in. */ com.f1j.swing.JBook workbook = new com.f1j.swing.JBook(); boolean needsReadWorkbook = true; com.f1j.ss.HTMLWriter htmlWriter = new com.f1j.ss.HTMLWriter(); </java> <HEAD> <TITLE>Southcreek Realty Co. - Instant Amortization</TITLE> </HEAD> <BODY> <BR> <BR> <BR> <CENTER><IMG SRC="topbannr.gif" WIDTH=400 HEIGHT=45 BORDER=0 ALT="Southcreek Realty"></CENTER><BR> <BR> <CENTER> <font point-size=8> <table><tr><td valign=top> <java> /*

300

Programming e.Spreadsheet Reports

* Suns Java Web Server allows embedded Java code in an HTML page * inside of <JAVA>...</JAVA> tags. * * This simple Java code will load a workbook, enter data into * the workbook, then output the workbook to an HTML page. */ // Gets the parameters from the form. String priceParam = request.getParameter("price"); String downParam = request.getParameter("down"); String closingParam = request.getParameter("closing"); String yearsParam = request.getParameter("years"); String interestParam = request.getParameter("interest"); // Makes sure the parameters have data in them. if ((priceParam != null) && (downParam != null) && (closingParam != null) && (yearsParam != null)) { java.io.Writer writer = new java.io.OutputStreamWriter(out); try { /* * Lock the workbook so that another request on another * thread will not conflict with this request. */ workbook.getBook().getLock(); try { if (needsReadWorkbook) { /* * Read in the workbook mortgage.vts from the server. * This workbook must be in the directory from which the * web server was run for this to work. */ htmlWriter.setFlags(htmlWriter.ALIGN_TAG | htmlWriter.VALUE_FORMATS | htmlWriter.BORDER_TAG); workbook.read("mortgage.vts", new com.f1j.ss.ReadParams()); needsReadWorkbook = false; } // Enter the data into the workbook workbook.setEntry(1, 3, priceParam); workbook.setEntry(2, 1, downParam); workbook.setEntry(4, 1, closingParam); workbook.setEntry(6, 3, yearsParam); workbook.setEntry(10, 4, interestParam);

Chapter 14, Deploying on a server

301

// Output the first table. htmlWriter.write(workbook, 0, 0, 0, 0, 19, 3, writer); // Outputs the amortization table. writer.write("</td><td valign=top>"); htmlWriter.write(workbook, 0, 31, 5, 0, yearsParam.equals("15") ? 46 : 61, 9, writer); } finally { /* * Release the lock. This must happen or no other thread * will be able to use the object. */ workbook.getBook().releaseLock(); } } catch (java.io.IOException e) { // Got an exception. Report it on the HTML page. writer.write("Got exception e=" + e.getMessage()); } catch (com.f1j.F1Exception e) { // Got an exception. Report it on the HTML page. writer.write("Got exception e=" + e.getMessage()); } } </java> </td></tr></table> </CENTER> </BODY> </HTML>

Accessing the API using JavaScript


To access the API using JavaScript: 1 Place f1j9swing.jar in a directory on the server. 2 Write an HTML page with at least the code in the code example below.

302

Programming e.Spreadsheet Reports

In the code example, the StartMeUp function is defined in JavaScript, and a call is made to the setShowEditBar method in e.Spreadsheet. The e.Spreadsheet object is named f1, and the name is set by adding the NAME parameter to the APPLET tag. This code must be run through Suns HTMLConverter program before viewing and can only be viewed using Suns Java 1.2.2 browser Plug-in. For more information, see Finding out which browsers are compatible with e.Spreadsheet in Chapter 13, Deploying on the Web.Finding out which browsers are compatible with e.Spreadsheet. The ARCHIVE path must lead to f1j9swing.jar. The following HTML assumes that f1j9swing.jar and empty.vts are in the same directory as the HTML page.

Code Example
<HTML> <HEAD> <SCRIPT> function startMeUp() { document.f1.getJBook().requestFocus(); document.f1.getJBook().setShowEditBar(true); } </SCRIPT> </HEAD> <BODY onload="startMeUp()" BGCOLOR="#FFFFFF"> <CENTER><APPLET CODE="com.f1j.swing.JBookApplet.class" ARCHIVE="./ f1j9swing.jar" NAME="f1" WIDTH=480 HEIGHT=360> <PARAM NAME="workbook" VALUE="./empty.vts"> </APPLET></CENTER> </BODY> </HTML>

Chapter 14, Deploying on a server

303

304

Programming e.Spreadsheet Reports

Part

5
Part 5

Working with e.Spreadsheet input and output

Part 5, Working with e.Spreadsheet input and output

305

306

Programming e.Spreadsheet Reports

Chapter

15
Chapter15

Reading and writing data

This chapter contains the following topics:


s s s

Reading and writing e.Spreadsheet files Ranges Images

Chapter 15, Reading and writing data

307

Reading and writing e.Spreadsheet files


With the most recent versions, support is added for:
s s s

file-level protection, UTF-8 and UTF-16 encoding, and merging data into existing data in a workbook to the several read . . . and write . . . methods in the Book, BookImpl, BookModel, and BookModelImpl classes.

These read and write methods also now include an argument (wp or rp) that references an object (WriteParams or ReadParams) containing information about the file type, passwords, character encoding, and data connection settings. For details, see Using ReadParams and WriteParams later in this chapter.Using ReadParams and WriteParams. In methods previously including no arguments, the WriteParams or ReadParams argument is added. In methods that previously included a fileType argument, that argument is replaced by WriteParams. All other read and write method arguments remain the same.

Code Examples
The simplest way to use the ReadParams or WriteParams object is to construct it with no arguments, using its default settings when writing a file as shown in the statements in the first example. Example 1: This example shows how to use ReadParams and WriteParams objects with no arguments. This statement writes a file in the current e.Spreadsheet file format with no special options:
com.f1j.swing.JBook book; // ... book.write("book.vts", new com.f1j.ss.WriteParams());

This statement reads a file using the default code page and no special options:
com.f1j.swing.JBook book; // ... book.read("book.vts", new com.f1j.ss.ReadParams());

Example 2:

308

Programming e.Spreadsheet Reports

These statements add a single argument. In this statement, the constructor accepts only a file format.
com.f1j.swing.JBook book; // ... book.write("book.xls", new com.f1j.ss.WriteParams(book.eFileExcel97));

In this statement, the constructor accepts only a code page.


com.f1j.swing.JBook book; // ... book.read("book.txt", new com.f1j.ss.ReadParams(book.eCodePageUTF8));

In this statement, the constructor accepts only a password.


com.f1j.swing.JBook book; // ... book.read("book.vts", new com.f1j.ss.ReadParams("what"));

Example 3: The set... methods of WriteParams and ReadParams return a reference to the WriteParams or ReadParams object so that various parameters may be set within a single statement. This statement writes three workbooks. The first workbook is saved in e.Spreadsheet version 6 format, the second as tabbed text using an 8-bit encoding of Unicode, and the third as Excel 97/2000 with a sheet level password.
com.f1j.swing.JBook book; // ... book.write("book1.vts", new com.f1j.ss.WriteParams(book.eFileFormulaOne6)); book.write("book2.txt", new com.f1j.ss.WriteParams(book.eFileTabbedText) .setCodePage(book.eCodePageUTF8)); book.write("book3.xls", new com.f1j.ss.WriteParams() .setFileType(book.eFileExcel97) .setOpenPassword("what"));

This example reads in three workbooks. The first statement reads in a text file and specifies the character set. The second statement reads in an Excel file with a sheet level password. The third set accesses the file "mymergefile" to specify the data connection information.

Chapter 15, Reading and writing data

309

com.f1j.swing.JBook book2; com.f1j.swing.JBook book3; com.f1j.swing.JBook book4; // ... book2.read("book2.txt", new com.f1j.ss.ReadParams() .setCodePage(book.eCodePageUTF8)); book3.read("book3.xls", new com.f1j.ss.ReadParams() .setPassword("what")); book4.read("book4.xls", new com.f1j.ss.ReadParams() .setDataPipesOverrideFile("mymergefile.properties"));

Earlier read, write, writeURL, writeToBlob, read and readFromBlob methods in the Book, BookImpl, BookModel, and BookModelImpl classes that do not reference a WriteParams or ReadParams object are now deprecated.

Using ReadParams and WriteParams


With ReadParams and WriteParams objects, e.Spreadsheet adds worksheet and workbook-level password protection and code pages. Code pages make it possible to specify the type of text encoding used to read or write files. Setting the file type, previously accomplished in the many individual write methods, is handled within the WriteParams object. The new classes also allow for the addition of future file reading and writing features without having to add new read and write methods.

Setting file type


Use the getFileType and setFileType methods in the ReadParams and WriteParams classes to return or set the file type. Workbooks created in e.Spreadsheet that are output in any of the Excel file formats (using the eFileExcel5, eFileExcel97, or eFileExcel97And5 parameters) are subject to the same limitations as any other Excel file, including limitations on the number of displayed significant digits (15) and the number of formatted cells (5,971 in most versions of Excel). For more information, see Exporting worksheets with more than 5,971 formatted cells to ExcelExporting worksheets with more than 5,971 formatted cells to Excel and Displaying more than 15 significant digits in Chapter 8, Formatting worksheets.Displaying more than 15 significant digits.

Syntax
setFileType(short eFileType)

310

Programming e.Spreadsheet Reports

Parameters
Parameter eFileType Description One of the following file type constants: eFileCurrentFormat eFileExcel5 eFileExcel97 eFileExcel97And5 Current file format Excel 5 (Excel 95) workbook file format Excel 8/9 (Office 97/2000) workbook file format Excel 5 (Office 95) 8/9 (Office 97/2000) workbook file format(s). Allows features from multiple Excel formats to be saved in one file and opened in several different Microsoft Office environments. Writes two copies of the workbook to the file, effectively doubling file size. version 3/4/5 file format version 6 file format version 7 file format Tabbed text format Values only tabbed text format Unicode text format Unicode tabbed text, valuesonly format

eFileFormulaOne3 eFileFormulaOne6 eFileFormulaOne7 eFileTabbedText eFileTabbedTextValuesOnly eFileUnicodeText eFileUnicodeTextValuesOnly

Using the e.Spreadsheet Designer


1 Choose FileSave As. 2 Select the desired file type from the Files of type: list. 3 Choose Save.

Code Example
This code saves the file exampletext.txt to the directory c:\files using the setFileType method to save the file as tabbed text.
jbook1.write("c:\\files\\exampletext.txt", new com.f1j.ss.WriteParams().setFileType(jbook1.eFileTabbedText));

Chapter 15, Reading and writing data

311

Setting code page type


Use one of the setCodePage methods to set the code page type for a file. The code page is the encoding method used to store text in a file.

Reading
When reading e.Spreadsheet and Excel files, e.Spreadsheet is able to determine the code page type based on the contents of the file. When reading tabbed text files, e.Spreadsheet may be unable to make such a determination. Calling the setCodePage method in the ReadParams class tells e.Spreadsheet which code page to assume when reading tabbed text files. Most Unicode (UTF-16) text files contain a byte order mark that enables e.Spreadsheet to determine the code page of such files. When creating Unicode tabbed text files, e.Spreadsheet always includes a byte order mark, but some other applications may not.

Writing
By default, e.Spreadsheet uses the default ANSI code page when writing tabbed text, version 3, or Excel 5 files, and the Unicode Little Endian code page for the newer e.Spreadsheet and Excel file formats. You may specify a different code page for tabbed text files, but not for the e.Spreadsheet or Excel formats. For Unicode text files, only the two UTF-16 code pages are possible: Unicode Little Endian or Unicode Big Endian. If the default ANSI code page is specified for a Unicode text file, e.Spreadsheet will default to Unicode Little Endian. Note that the Unicode and tabbed text file types are effectively identical when a UTF-16 code page is specified.

Syntax
setCodePage(int nCodePage)

Parameters:
Parameter nCodePage Description One of the following code page type constants:

312

Programming e.Spreadsheet Reports

Parameter

Description Code Page Type kCodePageDefaultANSI Description The default ANSI code page. This code page is compatible with Microsoft Windows and in most cases closely resembles the ISO 8859 standard. Unicode Little Endian (UTF-16) Unicode Big Endian (UTF-16) UTF-8 Integer 0

kCodePageUnicodeLE kCodePageUnicodeBE kCodePageUTF8

1200 1201 65001

Code Example
This example saves the file example.vts to the directory c:\files and sets the code page type to Unicode Little Endian using the setCodePage method.
jbook1.write("c:\\files\example.vts", new com.f1j.ss.WriteParams().setCodePage(jbook1.kCodePageUnicodeLE));

Setting password protection


Worksheet and workbook file level password protection is now included with e.Spreadsheet. The getPassword and setPassword methods in the ReadParams class control worksheet password protection. The getOpenPassword, setOpenPassword, getSavePassword, and setSavePassword methods in the WriteParams class control workbook file level protection.

Using the e.Spreadsheet Designer To add a password for a worksheet:


1 Choose ToolsProtectionProtect Sheet. 2 Type a password (up to 15 characters). 3 Choose OK. If no password is entered, the sheet is protected, but no password is required to unprotect the sheet.

Chapter 15, Reading and writing data

313

If a password is entered, a second Protect Sheet dialog appears. 4 Re-type the password. 5 Choose OK.

To remove a password from a worksheet:


1 Choose ToolsProtectionUnprotect Sheet to open the Protect Sheet dialog. 2 Type the password 3 Choose OK.

To add open and save passwords for a workbook file:


1 Choose ToolsProtectionFile Protection. 2 Type passwords (up to 15 characters) in Password to Open File and/or Password to Save File. 3 Re-type the passwords in Verify Password to Open File and Verify Password to Save File. 4 Choose OK. A message appears that reads, Changes to the file protection will take effect the next time you save the file. 5 Choose OK. 6 Save and close the file. The next time the file is opened the Password dialog will appear. Enter the open password and click enter to open the file.

To remove a password from a workbook file:


1 Choose ToolsProtectionFile Protection. 2 Delete the Open and/or Save passwords. 3 Choose OK. A message appears that reads, Changes to the file protection will take effect the next time you save the file. 4 Choose OK. 5 Save and close the file. The next time the file is opened the password protection is removed.

314

Programming e.Spreadsheet Reports

Code Example
This example saves the file example.vts to the c:\files directory using the setSavePassword and setOpenPassword methods to set the save file password to save sesame and the open file password to open sesame.
jbook1.write("c:\\files\example.vts", new com.f1j.ss.WriteParams() .setOpenPassword(open sesame) .setSavePassword("save sesame");

Setting external data connection information using a properties file


The setDataPipesOverrideFile method in the ReadParams class directs the ReadParams object to a properties file to use while opening a workbook file. This properties file, sometimes called a merge file, is a text file containing settings and information used to change the external data connection settings for the current workbook. External data connection properties may also be set by calling the setDataPipesOverrideProperties method with a java.util.Properties object. For more information and a code example, see Setting connection information with a properties file in Chapter 12, Connecting to external data.Setting connection information with a properties file.

Loading a worksheet with an embedded applet


To load a worksheet with an embedded applet, add the PARAM tag following the APPLET tag in the HTML code, as shown in the following example. Here, the file worksheet.vts is the VTS file you load into the applet:
<APPLET CODE = "com.f1j.swing.JBookApplet.class" WIDTH = 550 HEIGHT=375> <PARAM NAME = "workbook" VALUE = "worksheet.vts"> </APPLET>

Chapter 15, Reading and writing data

315

The PARAM NAME attribute has three settings, as shown in the following table. Name group Description Calls the setGroup method, setting the group name for the workbook attached to the current view. This allows external references between workbooks in the same group. Calls the attach method and attaches the current view to the specified views workbook. This allows multiple workbooks to display data from the same view. Workbooks must belong to the same group before they can be attached by name. Calls the readURL method and reads a workbook from the specified web page.

workbookname

workbook

Preventing setAllowInCellEditing from setting itself to true after saving and reloading a workbook
Call the saveWindowInfo method before calling the write method to prevent setAllowInCellEditing from setting itself to true. The saveWindowInfo method saves window specific information with the exported file.

Code Example
jbook1.setAllowInCellEditing(false); jbook1.saveWindowInfo(); jbook1.write(System.getProperty("user.dir") + java.io.File.separator + "test.xls", new com.f1j.ss.WriteParams(jbook1.eFileExcel97));

Adding multiple VTS files to one workbook


Normally, each VTS file is read in as a separate workbook. The code example below allows each of several VTS files read-in to be copied or pasted to a separate sheet tab within a single workbook.

Code Example
This code example copies both the objects and data from multiple files into a single workbook.

316

Programming e.Spreadsheet Reports

// Creates two JBooks and copies data from jbook1 to jbook2. jbook1 = new com.f1j.swing.JBook(); jbook2 = new com.f1j.swing.JBook(); getContentPane().add(jbook1); getContentPane().add(jbook2); setVisible(true); jbook1.setBounds(0, 0, 500, 250); jbook2.setBounds(0, 250, 500, 249); runCopyData(); public void runCopyData() { try { // Inserts the number of sheets/tabs needed in the new workbook. jbook2.insertSheets(1, numFiles - 1); // numFiles is the number of workbooks moved to the new workbook. for (int i = 0;i<numFiles;i++) { // Selects the sheet to paste the data onto. jbook2.setSheet(i); // Reads in the file to insert in a new sheet. jbook1.read("D:\\" + Files[i], new com.f1j.ss.ReadParams()); // Selects and copies all Objects from jbook1 to jbook2. if (jbook1.getFirstObject() != null){ // obj should be declared as a com.f1j.ss.GRObject obj = jbook1.getFirstObject(); while (obj != null) { jbook1.setSelection(obj); // Gets the location of the object on the worksheet. x1 = obj.getPos().getX1(); y1 = obj.getPos().getY1(); // Copies and pastes the object. For pasting objects, placement // accuracy of the object must be expressed in integers. jbook1.editCopy(); jbook2.setActiveCell((int)y1, (int)x1); jbook2.editPaste(); // Selects the next object to paste. obj = obj.getNextObject(); } } // Selects and copies all data in cells from jbook1 to jbook2.

Chapter 15, Reading and writing data

317

jbook1.setSelection(0, 0, jbook1.getLastRow(), jbook1.getLastCol()); jbook1.editCopy(); jbook2.setActiveCell(0, 0); jbook2.editPaste(); } } catch (com.f1j.util.F1Exception e1) { } catch (java.io.IOException e2) { } }

Writing to a Blob
Outputting a file to memory in a byte array
Use the writeToBlob method to output a file to memory in a byte array. Use the readFromBlob method to read a byte array stored in memory. The readFromBlob method also returns a ReadResults object describing the file it read in.

Code Example
jbook1.setText(0, 0, "12345"); byte blob[] = Jbook1.writeToBlob(new com.f1j.ss.WriteParams()); jbook1.initWorkbook(); com.f1j.ss.ReadResults readResults = jbook1.readFromBlob(blob, new com.f1j.ss.ReadParams());

Reading from and writing to a BLOB from an Enterprise JavaBean


When reading from or writing to a binary large object (BLOB) from within an Enterprise JavaBean (EJB), use only the read(blob[], ReadParams) or write(Sheet, WriteParams) methods in the class com.f1j.ss.Book. Call one of the read methods to load a spreadsheet into a book, or call the book.initBook method before calling this method.

Syntax
public com.f1j.ss.ReadResults read(byte blob[], com.f1j.ss.ReadParams rp);

318

Programming e.Spreadsheet Reports

public byte[] write(Sheet sheet, com.f1j.ss.WriteParams wp);

Parameters
Parameter blob[] rp Description Reference to the byte array to read from. A ReadParams object indicating how e.Spreadsheet will write the file. For details, see Using ReadParams and WriteParams later in this chapter.Using ReadParams and WriteParams. The sheet to write if the file type is a tabbed text or Unicode text type. This value is ignored for other file types and may be null. A WriteParams object indicating how e.Spreadsheet will write the file. For details, see Using ReadParams and WriteParams later in this chapter.Using ReadParams and WriteParams.

sheet

wp

Code Example
jbook1.setText(0, 0, "12345"); byte blob[] = Jbook1.writeToBlob(new com.f1j.ss.WriteParams()); jbook1.initWorkbook(); com.f1j.ss.ReadResults readResults = jbook1.readFromBlob(blob, new com.f1j.ss.ReadParams());

Determining BLOB length


To determine the length of a blob object, use the length member. See code example.

Code Example
This example outputs the file to memory in a byte array, reads the file in from a byte array in memory, and returns the total number of elements in the byte array using the length member.
byte blob[] = jbook1.writeToBlob(new com.f1j.ss.WriteParams()); jbook1.initWorkbook(); jbook1.readFromBlob(blob, new com.f1j.ss.ReadParams()); int i = blob.length;

Chapter 15, Reading and writing data

319

Writing to an output stream


To serialize a workbook and write to an output stream, use one of the write methods that includes a java.io.OutputStream parameter.

Syntax
public void write(java.io.OutputStream stream, int sheet1, int row1, int col1, int sheet2, int row2, int col2, WriteParams wp) public void write(java.io.OutputStream stream, WriteParams wp) public boolean write(Sheet sheet, java.io.OutputStream stream, WriteParams wp)

Call one of the read methods to load a spreadsheet into a book, or call the book.initBook method before calling this method.

Parameters
Parameter stream sheet sheet1 row1 col1 sheet2 row2 Description java.io.OutputStream that describes where to save the file. The sheet to write if the file type is eFileTabbedText or eFileTabbedTextValuesOnly. sheet number row number column number sheet number row number

320

Programming e.Spreadsheet Reports

Parameter col2 wp

Description (continued) column number A WriteParams object indicating how e.Spreadsheet will write the file. For details, see Using ReadParams and WriteParams earlier in this chapter.Using ReadParams and WriteParams.

Code Examples
The code examples below read and write serialized workbooks. Example 1: This example reads a serialized JBook from C:\F1Java\serialize.stt:
try { File fileSerialize = new File("c:\\F1Java\\serialize.stt"); FileInputStream fileIn = new FileInputStream(fileSerialize); ObjectInputStream oistream = new ObjectInputStream(fileIn); jbook1 = (com.f1j.swing.JBook)oistream.readObject(); oistream.close(); } catch (java.io.Exception){ }

Example 2: This code writes a serialized JBook to C:\F1Java\serialize.stt:


try { FileOutputStream fileOut = new FileOutputStream("c:\\F1Java\\serialize.stt"); ObjectOutputStream oostream = new ObjectOutputStream(fileOut); oostream.writeObject(jbook1); oostream.flush(); oostream.close(); } catch (java.io.Exception e) { }

Working with delimited text

Chapter 15, Reading and writing data

321

Converting data into tab-delimited text form


To convert a range of data to tab-delimited text use the getTabbedText method.

Syntax
public java.lang.String getTabbedText(int row1, int col1, int row2, int col2, boolean valuesOnly)

Parameters
Parameter row1 row2 col1 col2 valuesOnly Description The beginning row for the range. The ending row for the range. The beginning column for the range. The ending column for the range. Returns true if text is unformatted; false if text is formatted.

Code Example
String tabText = jbook1.getTabbedText(0, 0, jbook1.getLastRow(), jbook1.getLastCol(), true);

Writing a tab-delimited file


Use the eFileTabbedText parameter of the write method to write a worksheet as a tab-delimited file.

Using the e.Spreadsheet Designer


1 Choose FileSave As. 2 Select Tabbed Text or Tabbed Text Values Only from Files of Type.

Code Example
jbook1.write("C:\\F1Java\\tabbed.txt", new com.f1j.ss.WriteParams(jbook1.eFileTabbedText));

322

Programming e.Spreadsheet Reports

Writing a file as comma-delimited text


While e.Spreadsheet does not directly support comma-separated files, it does support tabbed text files. See Writing a tab-delimited file earlier in this chapter.Writing a tab-delimited file. To convert a file to a comma-delimited file, read in the file with e.Spreadsheet then use the getTabbedText method to get the data in tabbed text format. Convert the file to comma-delimited text and write it out.

Code Example
The following example saves the file in comma delimited text to C:\F1Java\ comma.txt.
String tabText = jbook1.getTabbedText(0, 0, jbook1.getLastRow(), jbook1.getLastCol(), true); char tabChar = \t; char commaChar = ,; String csvText = tabText.replace(tabChar, commaChar); java.io.File file = new java.io.File("C:\\F1Java","comma.txt"); java.io.FileOutputStream out = new java.io.FileOutputStream(file); out.write(String.valueOf(csvText).getBytes());

Preventing numbers from being interpreted as text when entering a tab-delimited text string
Insert the text using setFormula as shown in the code example. The code creates a tab-delimited text string, then outputs the text using setFormula to display it as a numerical value.

Code Example
jbook1.setText(0, 0, " " + "12345\t"); jbook1.setFormula(0, 1, jbook1.getText(0, 0));

Writing a file in Excel 2000 format


Since both Excel 97 and Excel 2000 have the same file format, use the eFileExcel97 constant with any of the write methods that can write a file in Excel 2000 format. All write methods except those that write only a range from a worksheet or that write to an HTML table can write a file in Excel format.

Chapter 15, Reading and writing data

323

Code Example
This example writes the file examplefile.xls to the local directory c:\files in Excel 2000 format.
jbook1.write("c:\\files\examplefile.xls", new com.f1j.ss.WriteParams(JBook.eFileExcel97));

Ranges
Converting an e.Spreadsheet range to XML
Use the XMLWriter class to convert ranges in e.Spreadsheet worksheets to XML data. The resulting XML data can be formatted using an XSLT document. For other ways to write and format XML data using e.Spreadsheet, see Using XML and XSLT in Chapter 12, Connecting to external data.Using XML and XSLT. For a table listing XML elements and attributes readable by e.Spreadsheet, see Importing XML using XSLT in Chapter 12, Connecting to external data.Importing XML using XSLT. The XMLWriter class outputs the following XML tags:

XMLWriter XML Output Schema


Tag <book> <sheet> <range> <row> name name index skip string (e.g. "Sheet1") string (e.g. "A1:G30" or "MergedRange" if ranges have been merged) number (the row number) number (of rows skipped prior to the last <row> element. Rows with formatting are not skipped) number (row height in twips, e.g. 240 = 12pt) Attribute Description

height-twips

324

Programming e.Spreadsheet Reports

Tag <cell>

Attribute width-twips hidden locked keys alignmenthorizontal alignment-vertical font-bold font-italic font-color font-size-twips merge-horizontal merge-vertical pattern-fg skip wrap

Description (continued) number (cell height in twips, e.g. 240 = 12pt) boolean (true = cell is hidden) boolean (true = cell is locked) string (a list of all defined names referring to this cell) string ("left," "center," "right") string ("top," "center," "bottom") boolean (true = bold) boolean (true = italic) RGB value (e.g. 0XFF0000 = red) number (e.g. 240 = 12pt) number (of cells merged to the right) number (of cells merged down) RGB value (e.g. 0XFF0000 = red) number (of cells skipped. Rows with formatting are not skipped) boolean (true = wrap cell text)

Code Example
This code writes out a range of data using the XMLWriter class and converts the data into HTML using the XSLT stylesheet file html.xsl (printed below) which comes with e.Spreadsheet. The code passes the range of the data to write out, the XSL file used to convert the data, and the output file.
import java.io.*; import java.awt.*; class XMLExample extends javax.swing.JFrame { private com.f1j.swing.JBook jbook1 = new com.f1j.swing.JBook(); private java.io.OutputStream xmlOutput; private java.io.InputStream xsltInput; private String outputRange; protected static String appPath = System.getProperty("user.dir") + java.io.File.separator; private static com.f1j.ss.XMLWriter xmlWriter;

Chapter 15, Reading and writing data

325

public XMLExample() { test(); } public void test() { try { // Sets up data to write out here, Or you can read in a file jbook1.read(appPath + "XMLExample.vts", new com.f1j.ss.ReadParams()); // Creates a file to output xmlOutput = new java.io.FileOutputStream(appPath + "HTMLExample.html"); // html.xsl, which comes with e.Spreadsheet, converts XML to HTML xsltInput = new java.io.FileInputStream(appPath + "html.xsl"); // Creates a new XMLWriter xmlWriter = new com.f1j.ss.XMLWriter(jbook1.getBook()); // Sets up the XMLWriter class to write out formatting xmlWriter.setWriteFormatAttributes(true); // Sets up the XMLWriter class to write out the tag "keys" for cells // referenced by a defined name xmlWriter.setWriteKeyAttributes(true); // Sets up the XMLWriter class to merge all ranges specified in the // write method into a single range of cells. xmlWriter.setMergeRangeType(com.f1j.ss.XMLWriter .eMergeRangeRows); // Uses an XSLT document to format the XML Output to HTML. // This method writes out a range. xmlWriter.write("A1:G15,A16:G38", xsltInput, xmlOutput); } catch(java.lang.Exception e1) { System.out.println(e1.getMessage()); } } public static void main(String[] args) { new XMLExample(); System.out.println("end"); System.exit(0); } }

326

Programming e.Spreadsheet Reports

Example XSL stylesheet


This is the file html.xsl referred to in the example code above. This file comes with e.Spreadsheet.
<?xml version="1.0" ?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" /> <xsl:template match="//sheet"> <table border="1" cellspacing="1" cellpadding="1" align="center"> <xsl:apply-templates select="range" /> </table> </xsl:template> <xsl:template match="row"> <xsl:call-template name="emptyrow"> <xsl:with-param name="skip"> <xsl:value-of select="@skip" /> </xsl:with-param> </xsl:call-template> <tr> <xsl:attribute name="height-twips"> <xsl:value-of select="@height-twips div 15" /> </xsl:attribute> <xsl:apply-templates select="cell[@height-twips>0]" /> <xsl:apply-templates select="cell" /> </tr> </xsl:template> <xsl:template match="cell"> <!--check for skip attribute and add </td> to skip table cells--> <xsl:call-template name="emptycell"> <xsl:with-param name="skip"> <xsl:value-of select="@skip" /> </xsl:with-param> </xsl:call-template> <td> <xsl:if test="string-length(@merge-horizontal)>0"> <xsl:attribute name="colspan"> <xsl:value-of select="@merge-horizontal" /> </xsl:attribute> </xsl:if> <xsl:if test="string-length(@merge-vertical)>0">

Chapter 15, Reading and writing data

327

<xsl:attribute name="rowspan"> <xsl:value-of select="@merge-vertical" /> </xsl:attribute> <xsl:attribute name="HEIGHT"> <xsl:value-of select="@merge-vertical" /> </xsl:attribute> </xsl:if> <xsl:call-template name="addTDattributes" /> <xsl:call-template name="addcelltext" /> </td> </xsl:template> <xsl:template name="addcelltext"> <DIV> <xsl:attribute name="style"> <xsl:if test="@font-color!="> color: # <xsl:value-of select="./@font-color" /> </xsl:if> <xsl:if test="@font-size-twips>0"> ; font-size: <xsl:value-of select="@font-size-twips div 20" /> pt </xsl:if> <xsl:if test="@pattern-fg!="> ; background: # <xsl:value-of select="./@pattern-fg" /> </xsl:if> <xsl:if test="@font-bold=true">; font-weight: bold</xsl:if> <xsl:if test="@font-italic=true">; font-style: italic</xsl:if> </xsl:attribute> <xsl:value-of select="./text()" /> </DIV> </xsl:template> <xsl:template name="addTDattributes"> <!-- DEFAULT VALUE - no attributes present --> <xsl:if test="string-length(@alignment-vertical)=0"> <xsl:attribute name="VALIGN">bottom</xsl:attribute> </xsl:if> <!-- need to calculate width value: not just take the one from F1 todo --> <xsl:if test="@width-twips>0 and string-length(@merge-horizontal)=0"> <xsl:attribute name="WIDTH"> <xsl:value-of select="@width-twips div 10" /> </xsl:attribute> </xsl:if> <xsl:if test="@alignment-horizontal!=">

328

Programming e.Spreadsheet Reports

<xsl:attribute name="ALIGN"> <xsl:value-of select="@alignment-horizontal" /> </xsl:attribute> </xsl:if> <xsl:if test="@alignment-vertical=bottom or @alignment-vertical=top"> <xsl:attribute name="VALIGN"> <xsl:value-of select="@alignment-vertical" /> </xsl:attribute> </xsl:if> <xsl:if test="@alignment-vertical=center"> <xsl:attribute name="VALIGN">MIDDLE</xsl:attribute> </xsl:if> <xsl:if test="@pattern-fg"> <xsl:attribute name="BGCOLOR"> # <xsl:value-of select="@pattern-fg" /> </xsl:attribute> </xsl:if> </xsl:template> <!-- adds "skip" <td/>s into the output document --> <xsl:template name="emptycell"> <xsl:param name="skip">0</xsl:param> <xsl:if test="$skip>0"> <td> <xsl:text disable-output-escaping="yes">&nbsp;</xsl:text> </td> <xsl:call-template name="emptycell"> <xsl:with-param name="skip"> <xsl:value-of select="$skip - 1" /> </xsl:with-param> </xsl:call-template> </xsl:if> </xsl:template> <!-- adds "skip" <tr/>s into the output document --> <xsl:template name="emptyrow"> <xsl:param name="skip">0</xsl:param> <xsl:if test="$skip>0"> <tr height="17" /> <xsl:call-template name="emptyrow"> <xsl:with-param name="skip"> <xsl:value-of select="$skip - 1" /> </xsl:with-param> </xsl:call-template> </xsl:if> </xsl:template>

Chapter 15, Reading and writing data

329

</xsl:stylesheet>

Writing a chart object as an image


The e.Spreadsheet API includes a class specifically designed to encode e.Spreadsheet chart objects as images. The ChartImageEncoder class contains methods that enable e.Spreadsheet to write a GRChart object in a worksheet to the GIF or PNG image formats or to create a custom class that writes the image to any format desired. This class also enables you to write out the charts image map using XSLT. The ChartImageEncoder class outputs the following XML tags:

ChartImageEncoder XML Output Schema


Tag <chartmap> Attribute Description name url <chart> <plot> <series> index name index <datapoint> <coords> <point/> x y </coords> </datapoint> <coords> <point/> x y number (the x coordinates of the series polygon) number (the y coordinates of the series polygon) number (the x coordinates of the enclosing polygon the clickable area for each datapoint) number (the y coordinates of the enclosing polygon the clickable area for each datapoint) name value number (series index number) string (series name) number (datapoint index number) string (datapoint name) number (datapoint value) string (name of chart image map passed to setImageMapName method) string (URL passed to setDefaultURL method)

330

Programming e.Spreadsheet Reports

Tag </coords> </series> <coords> <point/> </coords> </plot> <legend>

Attribute Description (continued)

x y

array (the x coordinates of the plot polygon) array (the y coordinates of the plot polygon)

index <legenditem> <coords> <point/> </coords> </legenditem> </legend> <coords> <point/> </coords> </chart> </chartmap> x y x y name

number (index number of each legend item) string (name of each legend item) array (the x coordinates of the legend item) array (the y coordinates of the legend item)

array (the x coordinates of the legend polygon) array (the y coordinates of the legend polygon)

Code Example
Example 1: This code dynamically creates an e.Spreadsheet chart, sets up parameters for writing out an image map, creates an image map of the chart, encodes the chart, writes the chart as an RLE GIF, then writes the image map to an HTML file using XSLT.
public class TestChart { public static void main(String[] args) { // Creates a JBook and aquires a lock com.f1j.swing.JBook book = new com.f1j.swing.JBook(); book.getLock();

Chapter 15, Reading and writing data

331

try { // Create a new chart book.setFormula(0, 0, "RANDBETWEEN(1,50)"); book.copyRange(0, 0, 5, 3, book, 0, 0, 0, 0, book.eCopyFormulas); com.f1j.ss.GRChart grChart = (com.f1j.ss.GRChart)book.addObject(com.f1j.ss.GRObject.eChart, 0, 0, 6, 18); grChart.setLinkRange("B1:D6", true); grChart.setTitle("TestTitle"); grChart.setName("TestChart"); // Create ImageEncoder com.f1j.swing.ChartImageEncoder ie = new com.f1j.swing.ChartImageEncoder(); // Do this only if an image map is needed ie.setCreateImageMap(true); // Create the chart image ie.encode(book, grChart); // Translate the image to a gif file java.awt.Image image = ie.getImage(); java.io.FileOutputStream gif = new java.io.FileOutputStream(System.getProperty("user.dir") + java.io.File.separator + "chart_img.gif"); ie.writeRLEGIF(gif); gif.close(); ////////////////////////////////// ///Build ImageMap/// ////////////////////////////////// String seriesName = "", mapStr = "", urlStr = "http://www.f1j.com", coordStr = ""; com.f1j.chart.ChartModel myModel = grChart.getChartModel(); java.awt.Polygon polyMap; mapStr = "<map name=\"mymap\">\n\r"; // Get LegendItem coordinates String legendNames[] = myModel.getLegendNames(); for(int i = 0; i < legendNames.length ; i ++) {

332

Programming e.Spreadsheet Reports

polyMap = ie.getImageMapLegendItemCoordinates(legendNames[i]); coordStr = polyToXYCoords(polyMap); mapStr += "<area shape=\"poly\" href=\"" + urlStr + "?legenditem=" + legendNames[i] + "\" coords=\"" + coordStr + "\" target=\"table\">\n\r"; } // Get Title coordinates polyMap = ie.getImageMapTitleCoordinates(); coordStr = polyToXYCoords(polyMap); mapStr += "<area shape=\"poly\" href=\"" + urlStr + "?title=" + grChart.getTitle() + "\" coords=\"" + coordStr + "\" target=\"table\">\n\r"; // Get data point coordinates for(int i = 0; i < myModel.getSeriesCount(); i++) { seriesName = myModel.getSeriesName(i); polyMap = ie.getImageMapSeriesCoordinates(seriesName); String pointNames[] = myModel.getDataPointNames(seriesName); for(int j = 0; j < pointNames.length ; j++) { java.awt.Polygon pointPoly = ie.getImageMapDataPointCoordinates(seriesName, pointNames[j]); coordStr = polyToXYCoords(pointPoly); mapStr += "<area shape=\"poly\" href=\"" + urlStr + "?datapoint=" + pointNames[j] + "&series=" + seriesName + "\" coords=\"" + coordStr + "\" alt=\"" + seriesName + " : " + "\" target=\"table\">\n\r"; } } mapStr += "</map>"; ////////////////////////////////////////// ///End Build ImageMap/// ////////////////////////////////////////// java.io.FileOutputStream myhtml = new java.io.FileOutputStream(System.getProperty("user.dir") + java.io.File.separator + "mymap.html"); myhtml.write(("<img src=\"./chart_img.gif\" border=\"0\" usemap=\"#mymap\">\n\r", new com.f1j.ss.WriteParams()).getBytes()); myhtml.write(mapStr.getBytes()); myhtml.close(); }

Chapter 15, Reading and writing data

333

catch(Exception e) { e.printStackTrace(); } finally { // Releases the JBook lock book.releaseLock(); System.exit(0); } } static public String polyToXYCoords(java.awt.Polygon poly) { String coordStr = ""; for(int i = 0; i < poly.xpoints.length; i++) { coordStr += poly.xpoints[i] + "," + poly.ypoints[i]; if (i != poly.xpoints.length - 1) coordStr += ","; } return coordStr; } }

Example 2: This code demonstrates writing an e.Spreadsheet chart object to the GIF image format using a custom class (CompressGIF.java, printed below).
public class TestChartB { public static void main(String[] args) { // Create a JBook and aquire a lock com.f1j.swing.JBook book = new com.f1j.swing.JBook(); book.getLock(); try { // Create a new chart book.setFormula(0, 0, "RANDBETWEEN(1,50)"); book.copyRange(0, 0, 5, 3, book, 0, 0, 0, 0, book.eCopyFormulas); com.f1j.ss.GRChart grChart = (com.f1j.ss.GRChart)book.addObject(com.f1j.ss.GRObject.eChart, 0, 0, 6, 18); grChart.setLinkRange("B1:D6", true); // Create ImageEncoder com.f1j.swing.ChartImageEncoder ie = new com.f1j.swing.ChartImageEncoder();

334

Programming e.Spreadsheet Reports

// Do this only if an image map is needed ie.setCreateImageMap(true); ie.setImageMapName("mymap"); ie.setImageMapDefaultUrl("http://www.f1j.com"); // Create the chart image ie.encode(book, grChart); // Translate the image to a gif file java.io.FileOutputStream gif = new java.io.FileOutputStream(System.getProperty("user.dir") + java.io.File.separator + "TestChartB.gif"); // Use the custom class CompressGIF to write the GIF ie.writeImage(gif, "CompressGIF"); // Create a file for the final output java.io.FileOutputStream html = new java.io.FileOutputStream(System.getProperty("user.dir") + java.io.File.separator + "TestChartB3.html"); // Opens an XSLT stylesheet file and processes the image map java.io.FileInputStream xslt = new java.io.FileInputStream(System.getProperty("user.dir") + java.io.File.separator + "imagemap.xsl"); // Write the image map ie.writeImageMap(xslt, html); // Close the streams gif.close(); xslt.close(); html.close(); } catch(Exception e) { e.printStackTrace(); } finally { // Release the JBook lock book.releaseLock(); System.exit(0); } } }

Chapter 15, Reading and writing data

335

This is the custom class used by the code above. This custom class must implement the com.f1j.swing.ImageCompressionIF interface. The following example uses classes from ACME Labs to create LZW compressed GIFs. A license from Unisys should be obtained before deploying this technology.
public class CompressGIF implements com.f1j.swing.ImageCompressionIF { public boolean compress(java.io.OutputStream out, java.awt.Image img) throws java.io.IOException { Acme.JPM.Encoders.GifEncoder ge = new Acme.JPM.Encoders.GifEncoder(img, out); ge.encode(); return true; } }

Example XSL stylesheet


<?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/ Transform"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" /> <xsl:strip-space elements="*" /> <xsl:template match="/chartmap"> <html> <body> <map name="{@name}"> <xsl:apply-templates select="chart/plot/series" /> </map> <img src="TestChart.gif" usemap="#mymap" border="0" /> </body> </html> </xsl:template> <xsl:template match="point"> <xsl:value-of select="@x" /> , <xsl:value-of select="@y" /> <xsl:if test="position() != last()"> <xsl:text>,</xsl:text> </xsl:if> </xsl:template> <xsl:template match="coords"> <area shape="poly"> <xsl:attribute name="coords">

336

Programming e.Spreadsheet Reports

<xsl:apply-templates /> </xsl:attribute> <xsl:attribute name="href"> <xsl:value-of select="/chartmap/@url" /> <xsl:text>/?</xsl:text> <xsl:for-each select="../@*"> <xsl:value-of select="name()" /> = <xsl:value-of select="." /> <xsl:if test="position() != last()"> <xsl:text>&</xsl:text> </xsl:if> </xsl:for-each> </xsl:attribute> </area> </xsl:template> </xsl:stylesheet>

Chapter 15, Reading and writing data

337

338

Programming e.Spreadsheet Reports

Chapter

16
Chapter16

Printing

This chapter contains the following sections:


s s s

Changing print settings Printing headers, footers, and titles Odds and Ends of Printing

Chapter 16, Printing

339

Changing print settings


Showing or hiding the print dialog
Calling the filePrint method with the print dialog flag set to false suppresses the print dialog. If the user-defined name Print_Area is defined, only those ranges specified in Print_Area are printed. If Print_Area is not defined, the entire formatted section of the worksheet is printed. With JDK1.1.x, the print dialog still appears after clicking the print button on the Standard toolbar in the e.Spreadsheet Designer or when calling filePrint with false. This is the result of a problem with JDK 1.1.x. The print button and filePrint method work correctly when e.Spreadsheet is running on the Java 2 Platform.

Syntax
public void filePrint(boolean showPrintDlg)

Parameters
Parameter showPrintDlg Description When set to true, the Print dialog displays before printing.

Code Example
jbook1.filePrint(false);

Setting print orientation to landscape


Calling the setPrintLandscape method with a parameter of true sets print orientation to landscape. Calling it with false sets print orientation to portrait. With JDK 1.1.x, setting the print orientation to landscape does not work. JDK 1.1.x did not allow this option to be set on a print job; the Java 2 Platform does.

Using the e.Spreadsheet Designer


1 Choose FilePage Setup. 2 Select Landscape under Orientation.

340

Programming e.Spreadsheet Reports

3 Choose Apply or OK.

Code Example
jbook1.setPrintLandscape(true);

Printing in landscape orientation using draw


Using JDK1.1.x, setting the print orientation to Landscape will not work. JDK 1.1.x did not allow this option to be set on a print job. Printing in Landscape using the draw method works correctly with the Java 2 platform. For more information and a code example, see Using draw to print in Chapter 8, Formatting worksheets.Using draw to print.

Getting print area information


Use the getPrintArea method to get print area information. The returned string is based on the user-defined name, Print_Area, which defines the worksheet range to be printed, in US English. The Print_Area definition can contain one or more ranges (e.g., A1:C3,A11:C13). If Print_Area is null (""), the selected portion of the active worksheet is printed.

Using the e.Spreadsheet Designer


1 Choose InsertName. 2 The named print area appears in the Formula text box. 3 If no print area is named, then none is currently defined and nothing appears in the window. See Setting print area correctly later in this chapterSetting print area correctly.

Code Example
String myPrintArea = jbook1.getPrintArea();

Setting the print scale to fit-to-page


Use the setPrintScaleFitToPage method in combination with the setPrintScaleFitVPages and setPrintScaleFitHPages methods to set the print scale to fit-to-page. The setPrintScaleFitVPages and setPrintScaleFitHPages methods have no effect unless the setPrintScaleFitToPage method is called with true.

Chapter 16, Printing

341

Code Example
jbook1.setPrintScaleFitToPage(true); jbook1.setPrintScaleFitHPages(1); // Fits print job to one page across jbook1.setPrintScaleFitVPages(2); // Fits print job to two pages down

Setting print area correctly


Use the setPrintArea method to set the print area. The setPrintArea method can contain one or more ranges (e.g. A1:C3,A11:C13). If Print_Area is Null (""), the selected portion of the active worksheet is printed. Set print areas as absolute ranges using the $ symbol (e.g. $A$1:$J$30). Setting the print area to a relative range (based on the active cell), may result in unexpected print output. A relative range is based on the active cell at the time the print area is set. If the active cell changes between the time the print area was set and the time the print occurs then an unexpected range is printed.

Using the e.Spreadsheet Designer


1 Select the cells you want to comprise the named print area. 2 Choose Print Area Set Print Area from the File menu. 3 An absolute print range is defined. See Getting print area information earlier in this chapterGetting print area information.

Code Example
The dollar sign ($) designates an absolute reference. The first example sets the print area to all cells from A1 to the last formatted row and column, the second example from A1 to J30, and the third example from A1 to D1.
jbook1.setPrintArea("$A$1:" + jbook1.formatRCNr(jbook1.getLastRow(), jbook1.getLastCol(), true)); jbook1.setPrintArea("$A$1:$J$30"); jbook1.setPrintArea("$A$1:$D$1");

Clearing the print area after using setPrintArea


To clear an existing print area, delete the Print_Area defined name.

Using the e.Spreadsheet Designer


1 Choose FilePrint AreaClear Print Area. Any existing defined print area is cleared.

342

Programming e.Spreadsheet Reports

Code Example
jbook1.deleteDefinedName("Print_Area");

Setting printing to black and white


Call the setPrintNoColor method with a parameter of true to print in black and white. Printing in black and white makes for a cleaner output and minimizes color printer driver problems. Using the setPrintNoColor option disables the ability to print patterns.

Code Example
Jbook1.setPrintNoColor(true);

Setting fit-to-page or fit-to-print using code


Calling the setPrintScaleFitToPage method with true fits the data to one page. Call the setPrintScale method with the desired print scale to scale the data instead.

Using the e.Spreadsheet Designer


1 Choose FilePage Setup. 2 Select the Page tab. 3 Set printing scale or fit to page in the Scaling section.

Code Example
Example 1: This code example fits the data to print on one page.
jbook1.setPrintScaleFitToPage(true);

Example 2: This code example scales the data to print at 50% of its current size.
jbook1.setPrintScale(50);

Chapter 16, Printing

343

Using fit-to-page or fit-to-print with multiple print ranges


To use the fitToPage or fit-to-print (setPrintScaleToFitPage) options with multiple print ranges requires five separate steps as illustrated in the code examples below: 1 Set the print area. 2 Call the setPrintScale method. 3 Set the fitToPage option to true. 4 Set the horizontal pages to 1 and vertical pages to the number of print areas. 5 Print. If you set the setPrintScaleToFitPage method to true and the horizontal and vertical number of pages are both 1, then the print area on the sheet will be scaled to about 1 x 1 in the upper left hand corner of the worksheet.

Using the e.Spreadsheet Designer


1 Holding down the Control key, use the mouse to select multiple ranges. 2 Choose FilePrint AreaSet Print Area. 3 Choose FilePage Setup. 4 Select the Page tab. 5 Adjust the Fit to Pages options to 1 page wide by the number of print areas high. 6 Choose OK

Code Example
try { // Fits each print area to one page. jbook1.setPrintArea("A1:A40, B2:G25"); // Sets the FitToPage argument to true, the Vertical pages to 1 and the // horizontal pages to the number of print areas. jbook1.setPrintScale(100, true, 1, 2); jbook1.filePrint(false); } catch (com.f1j.util.F1Exception err) { }

344

Programming e.Spreadsheet Reports

Scaling to fit-to-page horizontally only


Call the setPrintScale method with the fitToPage argument set to true, the Horizontal pages set to 1 and the Vertical pages set to a number much greater than the actual number of pages. The horizontal and vertical spacing will then scale proportionally and print only the pages it needs. For more information, see Printing to a specific scale or number of pages later in this chapter.Printing to a specific scale or number of pages.

Using the e.Spreadsheet Designer


1 Choose FilePage Setup. 2 Select the Page tab. 3 Adjust the Fit to Pages options to 1 page wide by 100 pages high.

Code Example
try { jbook1.setPrintScale(100, true, 100, 1); jbook1.filePrint(false); } catch (com.f1j.util.F1Exception err) { }

Changing the page setup attributes using code


Use the setPrint methods. The setPrint methods can handle all of the same page setup options available in the e.Spreadsheet Designer.

Method setPrintArea setPrintBottomMargin setPrintColHeading setPrintFooter setPrintFooterMargin setPrintGridLines setPrintHCenter setPrintHeader

Description Sets the print area. Sets the bottom print margin. Determines if column headings are printed. Sets the current page footer. Sets the margin for the footer from the bottom of the page. Determines if gridlines will be printed on the current sheet. Determines if the sheet is centered horizontally during printing. Sets the current page header.

Chapter 16, Printing

345

Method (continued) setPrintHeaderMargin setPrintLandscape setPrintLeftMargin setPrintLeftToRight

Description (continued) Sets the margin for the header from the bottom of the page. Determines the orientation of the print job. Sets the left print margin. Determines if the current sheet is printed from left to right then top to bottom, or from top to bottom then left to right. Determines if the print job is printed in black and white or color. Sets the right print margin. Determines if row headings are printed. Set the scale for the print job. Sets the number of horizontal pages. Determines if the Fit To option is on or off. Sets the number of vertical pages. Sets the print titles to be printed at the top of each page. Sets the top print margin. Determines if the sheet is centered vertically during printing.

setPrintNoColor setPrintRightMargin setPrintRowHeading setPrintScale setPrintScaleFitHPages setPrintScaleFitToPage setPrintScaleFitVPages setPrintTitles setPrintTopMargin setPrintVCenter

Printing headers, footers, and titles


Printing column and row headings
Calling the setPrintColHeading or setPrintRowHeading methods with true prints column or row headings.

Code Example
jbook1.setPrintColHeading(true); jbook1.setPrintRowHeading(true);

346

Programming e.Spreadsheet Reports

Formatting print headers and footers


To set formatting for headers and footers use the setPrintHeader and setPrintFooter methods and formatting codes.

Syntax
public void setPrintHeader(java.lang.String printHeader) public void setPrintFooter(java.lang.String printFooter)

Parameters
Parameter printHeader printFooter Description A text string that contains text and codes for the page header. A text string that contains text and codes for the page footer.

Special codes for the footer or header text.


Unless &L or &R is specified, text is centered. Code &L &C &R &A &D &T &F &P &P + number &P - number && &N \n Description Left-aligns the characters that follow. Centers the characters that follow. Right-aligns the characters that follow. Prints the sheet name. Prints the current date. Prints the current time. Prints the workbook name. Prints the page number. Prints the page number plus number. Prints the page number minus number. Prints an ampersand. Prints the total number of pages in the document. Inserts a carriage return.

Chapter 16, Printing

347

Font codes
Font codes must appear before other codes and text or they are ignored. Alignment codes (e.g., &L) restart each section. New font codes can be specified only after an alignment code.

Code &B &I &U &S &O &H &"fontname" &nn

Description Use a bold font. Use an italic font. Underline the header. Strikeout the header. Ignored (Mac specific). Ignored (Mac specific). Use the specified font. Use the specified font sizemust be a two digit number.

Using the e.Spreadsheet Designer


1 Choose FilePage Setup. 2 Select the Header/Footer tab. 3 Enter the following code in the Header: or Footer: text boxes:
&C&B&"Times New Roman"&16 Customer Survey

When the worksheet is printed, the text Customer Survey will print in the header or footer in centered, bold, 16 pt., Times New Roman font.

Code Example
This code example sets the Print Header to print the text Customer Survey in centered, bold, Times New Roman, 16 pt. font.
jbook1.setPrintHeader("&C&B&\"Times New Roman\"&16 Customer Survey");

348

Programming e.Spreadsheet Reports

Creating multiple-line print headers


To create multiple line print headers using code use the setPrintHeader method and the format code \n for carriage returns. Headers up to 256 characters long are supported in e.Spreadsheet.

Using the e.Spreadsheet Designer


1 Choose FilePage Setup. 2 Select the Headers/Footers tab. 3 Enter text and formatting codes in the Header: and Footer: text boxes.

Code Example
To create multiple line print headers using code: 1 Create a message string that uses the code \n for carriage returns. 2 Change the font size or style by changing the format codes. Format codes are listed in Formatting print headers and footers.Formatting print headers and footers. 3 Use the setPrintFooter method and the desired format code to position the page number. 4 Call the filePrint method with false to print the worksheet without the print dialog coming up.
String message = "&L This is to test printing a header. \n"; message + = "This is a test for doing subtitles. &R &D &T"; jbook1.setPrintHeader(message); jbook1.setPrintFooter("&R Page &P"); jbook1.filePrint(false);

Setting print titles


When setting print titles using code, make sure that the print title formulas use absolute references and that the entire row (e.g., $A$1:$IV$2) or column (e.g., $A$1:$C$16384) is selected.

Using the e.Spreadsheet Designer


To set print titles:

Chapter 16, Printing

349

1 Select the rows or columns to use as print titles. Select the entire row or column. 2 Choose FilePrint TitlesSet Print Titles. To remove previously set print titles: 1 Choose FilePrint Titles Clear Print Titles.

Code Example
This code example prints the print titles on each page, rows one and two and columns one and two, regardless of which part of the spreadsheet is printed.
jbook1.setPrintTitles("$A$1:$AVLH$2, $A$1:$B$" + jbook1.kMaxRow);

Printing row or column titles on every page


Use the setPrintTitles method to print row or column titles on every page. When specifying the range, make sure to specify the entire row or column.

Code Example
This code prints the first two rows and the first column on every page.
jbook1.setPrintTitles("A1:AVLH2, A1:A1073741824");

Printing headers and footers using draw


By default, the draw method prints the worksheet without headers and footers. To print headers and footers, send the header and footer text to the printer prior to calling the draw method.

Code Example
For more information and a code example, see Using draw to print in Chapter 8, Formatting worksheets.Using draw to print.

350

Programming e.Spreadsheet Reports

Odds and Ends of Printing


This section contains the following topics:
s s s s s

Printing to a specific scale or number of pages Printing a four-digit year in headers and footers Printing multiple jobs without running low on memory Preventing print jobs from producing large spool files Preventing print output from getting cut off

Chapter 16, Printing

351

Printing to a specific scale or number of pages


The getPrintScale and setPrintScale methods allow printing to a simple scale percentage or printing to fit the print job to a certain number of pages.

Syntax
public void setPrintScale(int scale, boolean fitToPage, int verticalPages, int horizontalPages)

Parameters
Parameter scale Description Indicates the scale factor. Scale factor can range from 10 to 400. To print a worksheet at the largest scale possible, set this value to 400, call setPrintScaleToFitPage with true, and specify the number of pages on which you want the worksheet printed. If set to true, the worksheet is scaled to fit in the number of pages specified by the verticalPages and horizontalPages parameters. If set to false, scale is used to print worksheet. The number of vertical pages to which the print job is fit. The number of horizontal pages to which the print job is fit.

fitToPage

verticalPages horizontalPages

Code Example
This code example sets the print scale to fit the full page size and get and display the current PrintScale settings.
jbook1.setPrintScale(400, true, 1, 1); jbook1.messageBox(jbook1.getPrintScale() + "," + jbook1.isPrintScaleFitToPage() + "," + jbook1.getPrintScaleFitVPages() + "," + jbook1.getPrintScaleFitHPages()," ",(short)1);

352

Programming e.Spreadsheet Reports

Printing a four-digit year in headers and footers


Use the setPrintHeader and setPrintFooter methods. Using the &D code prints the current date, but in the m/y/dd format. To set the year to a fourdigit format in headers and footers, build the print header or print footer string and concatenate in the data as a string. For more examples, see Formatting numbersFormatting numbers in Chapter 8, Formatting worksheets and Formatting print headers and footers earlier in this chapter.Formatting print headers and footers.

Using the e.Spreadsheet Designer


1 Choose FilePage Setup. 2 Select the Header/Footer tab. 3 Type the date in the desired format as a string in the header or footer textbox.

Code Example
This code example creates the four-digit date format and centers the date in the footer.
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("MMM dd, yyyy"); String todaysDate = dateFormat.format(new java.util.Date()); jbook1.setPrintFooter("&C" + todaysDate);

Printing multiple jobs without running low on memory


In Java, there is currently a significant delay before Java releases memory associated with printing. Developers can call System.gc() to immediately free the memory. The e.Spreadsheet Designer does not call the garbage collection routine, so users must wait for Java to call it. Printing multiple print jobs quickly from the e.Spreadsheet Designer could use up the available memory faster than Java can release it. Implementing the garbage collector in the e.Spreadsheet Designer is a current feature request.

Chapter 16, Printing

353

Preventing print jobs from producing large spool files


This is a limitation of the 1.2.x JDK. Java does not release memory used in printing back to the operating system. Calling System.gc() after each print helps. The garbage collector reclaims most if not more memory than was available before the print job. The e.Spreadsheet program has no control over the size of the spool files created by the JDK. Printing while running under JDK 1.3 creates significantly smaller spool files.

Preventing print output from getting cut off


This is a problem with Java not handling the unprintable area for a printer. The data gets shifted over by the unprintable area and can then get cut off. This can be compensated for by adjusting the margin width downward.

354

Programming e.Spreadsheet Reports

Chapter

17
Converting e.Spreadsheet data to HTML
Chapter 17

Chapter 17, Converting e.Spreadsheet data to HTML

355

Introduction
e.Spreadsheet uses a custom library of JSP tags, the JSP Charting API, to put spreadsheet data and charts into Web pages. The custom tags in the JSP Charting API encapsulate the complex Java code required to pull information out of spreadsheets and convert it into HTML. By specifying a few tags and parameters, a web designer can invoke complex Java code within JSP pages without having to know Java. With the JSP Charting API, developers can create images or HTML image maps of e.Spreadsheet charts, and HTML tables of e.Spreadsheet ranges for display Web pages.

Installing the JSP Charting API


Installing the JSP Charting API takes two main steps.

Step 1: Install the JSP Charting API test web app


The test web app is a basic installation of the JSP Charting API that serves as a diagnostic tool and reference implementation. It lets you know if you have to upgrade your web servers XML processor in order to support the JSP Charting API. The test web app is also the file source for later installing the JSP Charting API in your existing web application. If the test web app shows that your web server and XML processor are set up correctly, then you may proceed to installing the JSP Charting API in your web application.

Step 2: Install the JSP Charting API into an existing web application
In order to install the JSP Charting API in existing web applications, you copy the JSP Charting API classes from the test web app into the corresponding directory in your web application. There are two options:
s

As a solo web application You can create a brand-new web application or add the JSP Charting API to an existing web application. In either case, you copy JSP Charting API files from the test installation directory to another directory on your web server. You also need to make some changes to your web servers web.xml file, which provides configuration information for the JSP Charting API.

As a shared web application

356

Programming e.Spreadsheet Reports

If you have more than one web application that uses the JSP Charting API, you can install the JSP Charting API in a commonly accessible directory where all your web applications have access to it. This involves locating and moving JSP Charting API JAR files. You may have to edit server configuration files and startup scripts.

System requirements
You need the following hardware and software to install and run the JSP Charting API. All of these software packages must be installed before you can install the JSP Charting API.
s

A network server The server should contain enough memory and storage capacity to store the JSP Charting API classes and JAR files and to process JSP pages. The JSP Charting API software takes approximately 5 MB of disk space. UNIX machines that do not have a windowing environment require a graphics emulation package in order to fully use the JSP Charting API.

An Internet or network connection To publish your web pages on the Internet, your web server needs to be connected to an internet service provider. For internal or Intranet publishing, a local area network connection is all you need.

A web server with JSP support The JSP Charting API depends on a web server to process and display JSP pages containing JSP Charting API tags. See Web servers that support the JSP Charting API, later in this chapterWeb servers that support the JSP Charting API. You may use a web server that processes its own JSP tags, or you may use a separate JSP engine. For information on how to install and run your web server, see the web servers documentation. Any web server that is compliant with JSP 1.1 already contains (or requires you to install) a Java Runtime Environment (JRE). The JSP Charting API requires JRE version 1.2.2 or newer.

About the JSP Charting API test web app


Before installing the JSP Charting API directly in your web application, you must install the JSP Charting API test web app. For all web servers, the installation involves deploying the test web app and testing the installation. If your web server is not already JAXP 1.1-compliant, you must also install JAXP 1.1 support and then re-test. This step may not be necessary for all web servers.

Chapter 17, Converting e.Spreadsheet data to HTML

357

For installation instructions, see:


s

Installing the JSP Charting API under JRun later in this chapter.Installing the JSP Charting API under JRun. Installing the JSP Charting API under TomCat later in this chapter.Installing the JSP Charting API under TomCat.

Why do you need to install the test web app? The test web app is useful as a diagnostic tool. Since web servers are complicated pieces of software containing many directories and files, its easy to end up with files in the wrong places and missing files, resulting in errors. The test web app can help you determine where the error originated. Deploying the test web app installs the JSP Charting API Java classes in the appropriate directories in the web server. Its difficult to install these files and directories into a web application unless youve installed the test web app. Web designers who want to integrate the JSP Charting API into an existing web application can use the test web app as a source for JSP Charting API classes. Web designers who are starting from scratch may use the test web app as a basis for their web applications by copying the entire web application to a new name and modifying the JSP files. Finally, if you contact Actuate Corporations support department for help on the JSP Charting API, the first thing they will ask you is whether you installed the test web app and whether it works.

Web servers that support the JSP Charting API


This table lists the web servers that currently support the JSP Charting API and shows where you can find JSP Charting API installation documentation for each server. Other servers may support the JSP Charting API, but not all have been tested. Documentation on installing the JSP Charting API under additional web servers will be added as those servers come into compliance with the JSP Charting APIs basic requirements and are tested. The JSP Charting API only works with the specified release version of each server. Previous releases of these servers do not support the JSP Charting API. Web server JRun 3.x TomCat 3.2 Documentation See Installing the JSP Charting API under JRun later in this chapter.Installing the JSP Charting API under JRun See Installing the JSP Charting API under TomCat later in this chapterInstalling the JSP Charting API under TomCat

358

Programming e.Spreadsheet Reports

Beas WebLogic 6.0 web server supports most of JSP 1.1. However, its lack of support for certain key JSP 1.1 features (variables, for example) makes it unsuitable for working with this release of the JSP Charting API.

Installing the JSP Charting API under JRun


To install the JSP Charting API under JRun you install the test web app. The test web app is a basic installation of the JSP Charting API that serves as a diagnostic tool and reference implementation. It lets you know if you have to upgrade your web servers XML processor in order to support the JSP Charting API. The test web app is also the file source for later installing the JSP Charting API in your existing web application. To install the JSP Charting API under JRun, use JRuns administrative server and console as an installation and deployment tool. Perform the following procedures in order. For each procedure in the list, there is a corresponding section with detailed, step-by-step instructions. 1 Install the JSP Charting API test web app. 2 Test the installation of the test web app. 3 Upgrade JRuns XML parser, if necessary. Your installation of JRun may not contain the latest version of the XML parser. The JSP Charting API depends on an up-to-date version of the parser, so you may be required to upgrade your parser version.

How to install the test web app under JRun


1 Download the web archive file f1taginstall.war from the Actuate Corporation Web site or find it on your CD. You can store it in any directory on your hard drive. 2 Start the admin server and log into JRuns administrative console using your JRun administrative username and password. A browser may pop up automatically with a log-in screen, or you may have to open the browser yourself and go to the administrative console (usually http:// hostname:90). 3 After you log in, JRuns two-frame administrative console appears with a tree structure in the left frame. On that tree structure, open the node corresponding to the server where you want to install the JSP Charting API (generally either JRun Admin Server or JRun Default Server). 4 In the list of links that appears when you open the node, click on the Web Applications link. The right frame changes to a screen for editing, creating, deploying, and removing applications.

Chapter 17, Converting e.Spreadsheet data to HTML

359

5 In the right frame, click the link Deploy an Application. A web form appears with fields to be filled in as indicated in the following table. Field name Value to enter Explanation JRun extracts the test web app files from the WAR file you specify here. JRun automatically selects the server (either JRun Admin Server or JRun Default Server) you picked in an earlier step. This is the name of the test web app. This name appears in JRuns administrative console and in log files. If you have set up JRun as a multi-homing environment, where multiple Web site host names map to the IP address of a single Web server, this is where you specify the host names. This is the URL prefix used to access your test JSP pages. This is the directory in which JRun will install the test web app. This directory will become the document root for serving the test web apps files. You can install it in any directory, but we recommend you place it in a subdirectory of the JRun servers directory, where the other web applications are stored. You may create a new directory or install the software in an existing directory. Dont store more than one web application in the same directory, because files of the same name will be overwritten.

Servlet WAR File full path to f1taginstall.war JRun Server Name The selected server

Application Name

f1test

Application Host

All Hosts

Application URL Application Deploy Directory

/f1test full path to the test web app directory

For more information on any of these fields, see the JRun documentation.

360

Programming e.Spreadsheet Reports

6 Press the Deploy button. Wait a few moments until you see a message indicating the web application has been installed correctly. 7 Exit JRuns administrative console.

How to test installation of the test web app under JRun


1 Restart the JRun server (default or other) where you installed the test web app. 2 Point your browser to http://hostname:port/f1test/f1tagtest.jsp where hostname and port are the names of your server host and port. You should see a web page with a description of its own contents. If the page conforms to its self-description, you have successfully installed the test web app. If a JAXP1.1 compliance warning appears, you need to upgrade JRuns XML parser.

How to upgrade JRuns XML parser


1 Shut down all JRun servers. 2 Open the directory [jrun install directory]/lib/ext. Move the files jaxp.jar and parser.jar from that directory to a different directory for safekeeping. You probably wont need these files, which will be replaced during the upgrade, but you should keep copies of them just in case. 3 The test web app installation process created the subdirectory [serverpath]/f1test/jaxp11. Copy all the files in that directory to [jrun install directory]/lib/ext. 4 Restart the JRun server where you installed the test web app. 5 Reload the browser to display the file http://hostname:port/f1test/ f1tagtest.jsp where hostname and port are the names of your server host and port. The JAXP1.1 compliance warning shouldnt appear and the web page should display correctly, with a description of its own contents. If the page conforms to its self-description, you have successfully upgraded the XML parser.

Installing the JSP Charting API into a JRun web application


You can create a brand-new web application or add the JSP Charting API to an existing web application. The procedure is the same in both cases. Installing the JSP Charting API into a JRun web application involves the following tasks:

Chapter 17, Converting e.Spreadsheet data to HTML

361

Installing and testing the JSP Charting API test web app in order to ensure that the web server and the tag library software are compatible. Copying files from the installation directory of the test web app into the corresponding directory on your JSP web application. Setting JSP Charting API parameters. These parameters ensure that the web server can find 2 files necessary for proper processing of JSP Charting API tags. You set these parameters in the web.xml file, which serves as a storage place for web application parameters for servlets and tag libraries.

How to install the JSP Charting API into a JRun web application
The parameter settings described in these instructions can be found in the f1tagtest/WEB-INF/web.xml file that was copied onto your system during installation of the test web app. You can cut and paste the XML elements from that file into your web applications web.xml file. 1 Install and test the JSP Charting API test web application in JRun. You may have already done this step. If not, see Installing the JSP Charting API under JRun, earlier in this chapter.Installing the JSP Charting API under JRun. 2 Copy all files and directories in the [root of web application]/WEB-INF/ classes/com directory of the test web app to the same location in your existing web application. 3 Locate the web.xml file in the [root of web application]/WEB-INF directory. Open it in any text editor. 4 Add the following two XML elements to the web.xml file. These new elements can appear anywhere in the web.xml file, as long as they fall between the opening and closing <web-app> tags. The order of the parameters is not important. 1 Add the <taglib> element, shown below. This element defines the URI for the JSP Charting APIs TLD file. The TLD file defines the JSP Charting API tags and associated attributes.
<taglib> <taglib-uri>f1taglib</taglib-uri> <taglib-location> /WEB-INF/classes/com/f1j/taglib/taglib.tld </taglib-location> </taglib>

2 Add the following context parameter, which defines the location of the JSP Charting API properties file. You dont have to include this element if you are not using the JSP Charting API properties file to change the defaults of, override, or redefine attributes. For more information, see Using the properties file later in this chapter.Using the properties file.

362

Programming e.Spreadsheet Reports

<context-param> <param-name>f1taglib.mapfile</param-name> <param-value>/WEB-INF/installtest.properties</param-value> </context-param>

You can change the file name installtest in this element to whatever name you would like to give your properties file. 5 Save your changes to the web.xml file and close the text editor.

Sharing the JSP Charting API among JRun web applications


If your site requires the JSP Charting API software be shared between two or more web applications, you can install the JSP Charting API in a commonly accessible directory where all your web applications have access to it. This involves installing and configuring several files within JRun. After installation, you should go through a special testing process, documented in this section, in order to ensure that each web application is using the shared files. Once you decide to share the JSP Charting API on your server, it is very important to remove any existing installations of the JSP Charting API in individual web applications. You may either share the JSP Charting API among all web applications or install it in individual web applications. You cant do both. To install the JSP Charting API as a shared web application, perform the following procedures in order. For each procedure in the list, there is a corresponding section with detailed, step-by-step instructions. 1 Install JSP Charting API files as a shared application in JRun. First, youll install and test the JSP Charting API test web app in order to ensure that the web server and the tag library software are compatible. Next, youll copy JAR files from the installation CD or download packet into JRuns common library directory. By default, JRun and other web servers dont allow you to share individual class files. You must share classes bundled into JAR files. 2 Configure the JSP Charting API as a shared application in JRun. The configuration process ensures that the JSP Charting API tag library is available for all of the web applications running under JRun. The configuration changes are:
s

Defining the URI that appears on every JSP page that uses JSP Charting API tags. The URI points to the location of the JSP Charting API TLD file.

Chapter 17, Converting e.Spreadsheet data to HTML

363

Setting the location of the JSP Charting API TLD file, which defines the JSP Charting API tags and associated attributes. The above 2 changes are made in either JRuns global or local properties file.

Removing the URI from JRuns web.xml file Each web application has its own web.xml file which, among other things, defines the URI you use in your JSP pages and the location of the JSP Charting API TLD file. The entries you just added to the local.properties file do the same thing. Since the web.xml file overrides the local.properties file, you need to delete the appropriate elements from each web applications web.xml file in order to ensure that the values in local.properties are used.

Establishing the name and location of the JSP Charting API properties file for each web application, if you choose to use it. This file allows the web server administrator to change the defaults of, override, or redefine attributes. For more information, see Using the properties file later in this chapter.Using the properties file.

3 Test the shared installation in JRun. The class files that were installed as part of your test web app are the same classes found in the JAR files that you installed in the shared directory. The final test for ensuring your shared install works properly is to delete the JSP Charting API class files from the test web app, then view the sample JSP file from that test web app. If the sample JSP file appears correctly, then you know that the shared installation was installed and configured correctly and the web server is using the shared files. Even if you dont want to perform this test, its a good idea to remove these files so that you dont have duplicate files on your server.

How to install JSP Charting API files as a shared application in JRun


1 Install and test the JSP Charting API test web application in JRun. You may have already done this step. If not, see Installing the JSP Charting API under JRun, earlier in this chapterInstalling the JSP Charting API under JRun. 2 Locate the JAR files f1j9swing.jar, f1j9taglib.jar, and f1jtextures.jar on the product CD. If you do not use textured fills in your spreadsheet, you will not need the f1jtextures.jar file. Copy the JAR files into the [jrun install directory]/servers/[server directory]/lib directory.

364

Programming e.Spreadsheet Reports

How to configure the JSP Charting API as a shared application in JRun


1 In the JRun properties file, establish the JSP Charting API URI and set the location for the taglib.tld file. 1 Choose which copy of JRuns properties file you want to edit. Each JRun web application contains a properties file at [jrun install directory]/ servers/[server name]/local.properties, where [jrun install directory] is the directory in which JRun is installed and [server name] is the name of the server where the JSP Charting API is deployed. There is also a global properties file for all JRun servers and web applications at [jrun install directory]/lib/global.properties. 2 Open the JRun properties file of your choice in a text editor and add the following lines to the file:
web-app.taglib-uri.f1taglib=/WEB-INF/jrun/f1taglib.jar webapp.path-mapping./WEB-INF/jrun/f1taglib.jar= {jrun.server.rootdir}\\lib\\f1j9taglib.jar

The code between the braces is a variable name in JRun. Make sure you type this code in correctly. The first line of code defines the name of the tag librarys URI (f1taglib) and also indicates a pseudo-directory (/WEB-INF/jrun/f1taglib.jar). The second line maps that pseudo-directory to the JAR file f1j9taglib.jar in an actual directory on the server. This indirect definition is necessary because web applications cant access files outside of their own root directories. The TLD file is located in f1j9taglib.jar, in META-INF/ taglib.tld, which is the well known location for TLDs within JAR files. 2 Restart the server to force JRun to read in the changes in the properties file. 3 Remove the URI from JRuns web.xml file. 1 Locate each web applications web.xml file, which can be found in the [web application]/WEB-INF directory. 2 Open the web.xml file in a text editor. 3 Change each web applications web.xml file by removing the <taglib></taglib> tags and all text between those tags. This ensures that there are no values in any of the web.xml files that might override the URI settings you already established in the local.properties file. 4 Establish the name and location of the JSP Charting API properties file for each web application, if you choose to use it. 1 Locate the web.xml file for each web application in which you want to establish a JSP Charting API properties file. The web.xml file can be found in the [web application]/WEB-INF directory.

Chapter 17, Converting e.Spreadsheet data to HTML

365

2 Open the web.xml file in a text editor. 3 Enter the following XML element in the web.xml file:
<context-param> <param-name>f1taglib.mapfile</param-name> <param-value>/WEB-INF/installtest.properties</param-value> </context-param>

You can change the file name installtest in this element to whatever name you would like to give your properties file.

How to test a shared installation of the JSP Charting API in JRun


1 Remove all files in the [test web app directory]/WEB-INF/classes/com directory and all subdirectories. 2 Point your browser to the JSP test file at http://hostname:port/f1tagtest/ f1tagtest.jsp where hostname and port are the names of your server host and port. You should see a web page with a description of its own contents. If the page conforms to its self-description, you have successfully shared the JSP Charting API among your web applications.

Installing the JSP Charting API under TomCat


To install the JSP Charting API under TomCat, you install the test web app. The test web app is a basic installation of the JSP Charting API that serves as a diagnostic tool and reference implementation. It lets you know if you have to upgrade your web servers XML processor in order to support the JSP Charting API. The test web app is also the file source for later installing the JSP Charting API in your existing web application. For more information about the test web app and why you need to install it, see About the JSP Charting API test web appearlier in this chapter.About the JSP Charting API test web app. To install the test web app, perform the following procedures in order. For each procedure in the list, there is a corresponding section with detailed, stepby-step instructions. 1 Install the JSP Charting API test web app. The installation is done by copying the JSP Charting API WAR file into the webapps subdirectory of TomCats install directory and restarting the TomCat server. Each time TomCat starts up, it un-jars any web application WAR files it finds in that directory. 2 Test the installation of the test web app.

366

Programming e.Spreadsheet Reports

3 Upgrade TomCats XML parser, if necessary. Your installation of TomCat may not contain the latest version of the XML parser. The JSP Charting API depends on an up-to-date version of the parser, so you may be required to upgrade your parser version. When running TomCat on UNIX, you must set and export the JAVA_HOME variable to point to your JDK or JRE before starting TomCat. Otherwise, TomCat will not have access to the Swing classes and the JSP Charting API will not be able to create charts.

How to install the test web app under TomCat


1 Download the web archive file f1taginstall.war from the Actuate Corporation Web site or find it on your CD. 2 Shut down the TomCat server if it is already running. 3 Copy the file f1taginstall.war into the [tomcat32 root directory]/webapps directory. 4 Restart the TomCat server. When the server restarts, it un-jars the JSP Charting API WAR file and places the class files in the appropriate directories.

How to test installation of the test web app under TomCat


1 Make sure the server has been restarted. 2 Point your browser to http://hostname:port/f1taginstall/f1tagtest.jsp where hostname and port are the names of your server host and port. You should see a web page with a description of its own contents. If the page conforms to its self-description, you have successfully installed the test web app. If a JAXP1.1 compliance warning appears, you need to upgrade TomCats XML parser.

How to upgrade TomCats XML parser


1 Shut down the TomCat server. 2 Open the directory [tomcat home directory]/lib. Move the files jaxp.jar and parser.jar from that directory to a different directory for safekeeping. You probably wont need these files, which will be replaced during the upgrade, but you should keep copies of them just in case. 3 The test web app deployment process created the subdirectory [tomcat home directory]/webapps/f1taginstall/jaxp11. Copy all the files in that directory to [tomcat home directory]/lib. 4 Restart the TomCat server.

Chapter 17, Converting e.Spreadsheet data to HTML

367

5 Reload the browser to display the file http://hostname:port/f1taginstall/ f1tagtest.jsp where hostname and port are the names of your server host and port. The JAXP1.1 compliance warning shouldnt appear and the web page should display correctly, with a description of its own contents. If the page conforms to its self-description, you have successfully upgraded the XML parser.

Installing the JSP Charting API into a TomCat web application


You can create a brand-new web application, or you can add the JSP Charting API to an existing web application. The procedure is the same in both cases. Installing the JSP Charting API into a TomCat web application involves the following tasks:
s

Installing and testing the JSP Charting API test web application in order to ensure that the web server and the tag library software are compatible. Copying files from the installation directory of the test web application into the corresponding directory in the TomCat web application. Setting JSP Charting API parameters. These parameters ensure that the web server can find 2 files necessary for proper processing of JSP Charting API tags. You set these parameters in the web.xml file, which serves as a storage place for web application parameters for servlets and tag libraries.

How to install the JSP Charting API into a TomCat web application
The parameter settings described here can be found in the f1taginstall/WEBINF/web.xml file that was copied onto your system during installation of the test web app. You can cut and paste the XML elements from that file into your web applications web.xml file. 1 Install and test the JSP Charting API test web application in TomCat. You may have already done this step. If not, see Installing the JSP Charting API under TomCat, earlier in this chapterInstalling the JSP Charting API under TomCat. 2 Copy all files and directories in the [root of web application]/WEB-INF/ classes/com directory of the test web app to the same location in your existing web application. 3 Locate the web.xml file in the [root of web application]/WEB-INF directory. Open it with any text editor. 4 Add the following two XML elements to the web.xml file. These new elements can appear anywhere in the web.xml file, as long as they fall

368

Programming e.Spreadsheet Reports

between the opening and closing <web-app> tags. The order of the parameters is not important. 1 Add the <taglib> element, shown below. This element defines the URI for the JSP Charting APIs TLD file. The TLD file defines the JSP Charting API tags and associated attributes.
<taglib> <taglib-uri>f1taglib</taglib-uri> <taglib-location> /WEB-INF/classes/com/f1j/taglib/taglib.tld </taglib-location> </taglib>

2 Add the following context parameter, which defines the location of the JSP Charting API properties file. You dont have to include this element if you are not using the JSP Charting APIs properties file to change the defaults of, override, or redefine attributes. For more information, see Using the properties file later in this chapter.Using the properties file.
<context-param> <param-name>f1taglib.mapfile</param-name> <param-value>/WEB-INF/installtest.properties</param-value> </context-param>

You can change the file name installtest in this element to whatever name you would like to give your properties file. 5 Save your changes to the web.xml file and close the text editor.

Sharing the JSP Charting API among TomCat web applications


If your site requires the JSP Charting API software be shared between two or more web applications, you can install the JSP Charting API in a commonly accessible directory where all your web applications have access to it. This involves installing and configuring several files within TomCat. After installation, you should go through a special testing process, documented in this section, in order to ensure that each web application is using the shared files. Once you decide to share the JSP Charting API on your server, it is very important to remove any existing installations of the JSP Charting API in individual web applications. You may either share the JSP Charting API among all web applications or install it in individual web applications. You cant do both. To install the JSP Charting API as a shared web application, perform the following procedures in order. For each procedure in the list, there is a corresponding section with detailed, step-by-step instructions.

Chapter 17, Converting e.Spreadsheet data to HTML

369

1 Install JSP Charting API files as a shared application in TomCat. First, youll install and test the JSP Charting API test web application in order to ensure that the web server and the tag library software are compatible. Next, youll copy JAR files from the installation CD or download packet into TomCats common library directory. By default, web servers dont allow you to share individual class files. You must share classes bundled into JAR files. 2 Configure the JSP Charting API as a shared application in TomCat. The configuration process ensures that the JSP Charting API tag library is available for all of the web applications running under TomCat. The configuration changes are:
s

Defining the URI that appears on every JSP page that uses JSP Charting API tags. The URI points to the location of the JSP Charting API TLD file. Setting the location of the JSP Charting API TLD file, which defines the JSP Charting API tags and associated attributes. Establishing the name and location of the JSP Charting API properties file for each web application, if you choose to use it. This file allows the web server administrator to change the defaults of, override, or redefine attributes. For more information on the properties file, see Using the properties file later in this chapter.Using the properties file. All three of the above changes are made in TomCats web.xml file.

Copying the taglib.tld file into the appropriate directory for each of the shared web servers that processes JSP Charting API tags.

3 Test the shared installation in TomCat. The class files that were installed as part of your test web app are the same classes found in the JAR files that you installed in the shared directory. The final test for ensuring your shared install works properly is to delete the JSP Charting API class files from the test web app, then view the sample JSP file from that test web app. If the sample JSP file appears correctly, then you know the shared installation was installed and configured correctly and the web server is using the shared files. Even if you dont want to perform this test, its a good idea to remove these files so that you dont have duplicate files on your server.

370

Programming e.Spreadsheet Reports

How to install JSP Charting API files as a shared application in TomCat


1 Install and test the JSP Charting API test web application in TomCat. You may have already done this step. If not, see Installing the JSP Charting API under TomCat, earlier in this chapterInstalling the JSP Charting API under TomCat. 2 Locate the JAR files f1j9swing.jar, f1j9taglib.jar, and f1jtextures.jar on the the product CD or in the download packet, if you downloaded e.Spreadsheet from the web. (If you do not use textured fills in your spreadsheet, you will not need the f1jtextures.jar file.) Copy the JAR files into the [tomcat install directory]/lib directory.

How to configure the JSP Charting API as a shared application in TomCat


1 In the web.xml file, establish the JSP Charting API URI and set the location for the taglib.tld file. 1 Choose which copy of web.xml you want to edit. Each TomCat web application contains a web.xml file, but there is also a default web.xml file located in [tomcat install directory]/conf. You can choose whether to change that one file or change each web applications copy of web.xml. 2 Add this element to the web.xml file you chose.
<taglib> <taglib-uri>f1taglib</taglib-uri> <taglib-location>/WEB-INF/taglib.tld</taglib-location> </taglib>

2 If you want to use the JSP Charting API properties file, establish the name and location of that file. 1 Choose whether you want to have one default properties file for all your web applications or an individual properties file for each web application. This decision drives which web.xml file you will edit next. - To establish a default properties file, use TomCats default web.xml file at [tomcat install directory]/conf/web.xml. - To establish a properties file for a particular web application, use each web applications web.xml file at [web application]/WEB-INF/ web.xml. 2 Add the following element to the web.xml file that you chose. This element establishes the name and location of the properties file.
<context-param> <param-name>f1taglib.mapfile</param-name> <param-value>/WEB-INF/installtest.properties</param-value>

Chapter 17, Converting e.Spreadsheet data to HTML

371

</context-param>

You can change the file name installtest in this element to whatever name you would like to give your properties file, but be sure to match the name of the actual properties file with the name you create here. 3 Copy the taglib.tld file from the [test web app directory]/WEB-INF/ classes/com/f1j/taglib directory into the WEB-INF directory of each web application that uses the tag library.

How to test a shared installation of the JSP Charting API in TomCat


1 Copy the taglib.tld file from the [test web app directory]/WEB-INF/ classes/com/f1j/taglib directory into the [test web app directory]/WEBINF directory. 2 Remove all files from the directory [test web app directory]/WEB-INF/ classes/com. 3 Make the same configuration changes to the test web app as you did to your other web applications. See How to configure the JSP Charting API as a shared application in TomCat, earlier in this chapterHow to configure the JSP Charting API as a shared application in TomCat for an explanation of the configuration file changes you need to make. You have already done the last of the configuration changes, which is moving the TLD file. 4 Test the shared installation by pointing your browser to the JSP test file at http://hostname:port/f1taginstall/f1tagtest.jsp where hostname and port are the names of your server host and port. You should see a web page with a description of its own contents. If the page conforms to its self-description, you have successfully shared the JSP Charting API among your web applications.

Using tags
The JSP Charting API functions within a web server and requires a JSP engine. The web server processes requests for particular JSP files; the JSP engine processes the JSP tags (including the JSP Charting API tags) within JSP files.

Structure of a JSP Charting API tag


JSP Charting API tags follow standard XML syntax. They are made up of an opening and a closing tag consisting of text between two sets of angle brackets, like this:
<f1:TagName attribute="attribute_value">

372

Programming e.Spreadsheet Reports

... </f1:TagName>

You can put JSP or HTML code between the opening and closing tags. This table describes the parts of JSP Charting API tags. Tag part < > f1: Description Angle brackets enclose each tag. The tag prefix (in this case f1:) informs the JSP processor which tag library this tag belongs to. To set what the prefix will be for a particular JSP page, you use a line of JSP code called the taglib directive. For more information, see About the taglib directive, later in this chapter.About the taglib directive. All of the tag examples in this documentation use the prefix f1. This is the name of the tag. You must spell and capitalize it exactly as its shown in the tags documentation. See Tag reference later in this chapterTag reference for the tag names and spellings. Attributes are parameters that let you modify the tags default behavior and specify which workbooks and other documents the tag should work on. For more information, see About attributes later in this chapter.About attributes. This is the value of the attribute. For example, the value of the attribute book will be the name of a particular workbook. For more information, see About attributes later in this chapter.About attributes. The forward slash closes up the closing tag.

TagName

attribute

"attribute_value"

If a tag requires no text between its opening and closing tags, the tag can be abbreviated by placing the forward slash before the final angle bracket. This closes up the tag:
<f1:TagName attribute="attribute_value"/>

This type of tag does not have a body, while the tag described above does. For more information on these two types of tags, see Tags with bodies and tags without bodies, later in this chapter.Tags with bodies and tags without bodies.

Chapter 17, Converting e.Spreadsheet data to HTML

373

Tags with bodies and tags without bodies


There are two types of tags: tags without bodies and tags with bodies.
s

Tags without bodies Tags without bodies do not contain JSP or HTML code. They are selfcontained. Tags without bodies consist of the tag prefix and name, any tag attributes and their values, and a forward slash. For example, the InsertVersion tag, below, has no body and no attributes. It inserts the version of the JSP Charting API that you are using, along with some other information.
<f1:InsertVersion/>

Tags with bodies Tags with bodies allow HTML and JSP code between an opening and closing tag. The opening tag contains the tag prefix, tag name, and any tag attributes and their values. The closing tag contains a forward slash followed by the tag prefix and name. You insert JSP code between those two tags. For example, the GetCell tag has a body in which you can insert JSP code to display or calculate the value of the specified cell. In the following example, the GetCell tag retrieves the value of cell A1 from a workbook called book1. It stores the value in the predefined getCellValue variable, which it then outputs using the <%= ... %> JSP syntax.
<f1:GetCell book="book1" cell="A1" value="true"> <%= dGetCellValue %> </f1:GetCell>

About attributes
Almost all tags have attributes that parameterize the output of the tag. For example, many of the tags have a book attribute, which you use to specify which workbook contains the information the tag needs. Attributes can also function like switches that let you turn on or off certain parts of a tags functionality. When you write JSP code using JSP Charting API tags, you must spell each attribute name exactly as its shown in Tag reference later in this chapter.Tag reference. All JSP Charting API attributes and their values are lowercase. You must enclose attribute values in either single or double quotation marks.

Setting attribute values


All attributes must specify either a value or an empty string (indicated by empty quotation marks). For example, the value of the attribute book is the

374

Programming e.Spreadsheet Reports

name of a particular workbook. Attribute values must be enclosed in either single or double quotation marks because the tags follow XML syntax. Some attribute values are restricted to a certain set of values, for example, true or false. These values must be spelled exactly as indicated in the documentation. See Tag reference later in this chapterTag reference for a list of the tags, their attributes, and specified attribute values.

About the book and source attributes


The LoadBook tag contains both a source and a book attribute. The source attribute refers to a VTS (e.Spreadsheet) or XLS (Microsoft Excel) file. The book attribute creates a nickname for that file. You use this nickname, not the actual path and name of the file, as the value of the book attribute in other JSP Charting API tags. You must load a VTS or XLS file with the LoadBook tag before you may refer to that book in any other JSP Charting API tag. The LoadBook tags source attribute can refer to a VTS or XLS file in any of the following ways:
s

the relative path to a VTS or XLS file stored on the server. For example, ../ ../sample.vts the file name and protocol of a VTS or XLS file stored on another server. For example, http://www.actuate.com/examples/sample.xls a default, override, or redefined attribute value for a VTS or XLS file, as established in the JSP Charting API properties file. For more information, see Using the properties file later in this chapter.Using the properties file.

About variables
A variable is a placeholder that holds information temporarily. Some of the JSP Charting API tags populate predefined variables. When the tag is processed, these variables are set automatically. You can use these variables in JSP code. Different variables deliver the requested data in different forms. For example, the GetCell tag has a variable called dGetCellValue that contains the contents of a specified cell in a specified workbook. You can output the value of dGetCellValue using JSP code, you can use that value in a calculation, etc. If you change the GetCell tags attributes to specify a different cell or the workbook, the variables value changes. When you write JSP code using JSP Charting API tags, you must spell and capitalize each variable name exactly as its shown in Tag reference later in this chapter.Tag reference.

Chapter 17, Converting e.Spreadsheet data to HTML

375

About variable names


The first few letters of a variables name indicate the data type of that variable. Those letters area lowercase, but the variable name itself is proper case, as shown below. Data type double int string byte Variable naming convention dVariableName iVariableName strVariableName byVariableName

About variable scope


The value of a variable changes as the program runs through the JSP code. Scope is the area of the code in which the variable is available. Depending on the tag, the contents of the variable may change within the processing of the tag. For all variables created by the JSP Charting API tags, the scope of the variable is between the opening and closing tags. For example, the strGetCellText variable of the GetCell tag is defined only in between the opening and closing GetCell tags. In other areas of the JSP page that contains the GetCell tag, the strGetCellText variable cant be used because it hasnt been defined. If you attempt to use it outside of the GetCell tag, it will generate a compiler error.

About variables in ForEach tags


All the tags that begin with ForEach (ForEachDatapoint, ForEachLegend, and ForEachSeries) perform the code between the opening and closing tags once for each item in a series of similar data. In these tags, each variables value is set before any of the JSP code between the opening and closing ForEach tag is performed for the first time. When the first loop is finished, the values are reset and the JSP code is run for the second time. For each iteration, the variable value is reset before the code is run.

About single-element array variables


Some JSP Charting API variables are defined as single-element arrays. The rationale for using single-element arrays is that JSP only allows variables of type Object to be passed between the tags and the servlet code. Since the data types Integer and Double are immutable, each time a variable of one of those data types is set, a new instance has to be created. Using a variable defined as a single-element array allows the tag to return the native type (int rather than Integer) as well as reuse the instance each iteration. This saves time and memory.

376

Programming e.Spreadsheet Reports

In the documentation, single-element array variables have [0] following the variable name. They are:
s s s s s s s s s s

dGetCellValue[0] variable of the GetCell tag iDatapointCount[0] variable of the ForEachDatapoint tag iDatapointPosition[0] variable of the ForEachDatapoint tag iGetRangeColumnCount[0] variable of the GetRange tag iGetRangeRowCount[0] variable of the GetRange tag iGetRangeSheetCount[0] variable of the GetRange tag iLegendCount[0] variable of the ForEachLegend tag iLegendPosition[0] variable of the ForEachLegend tag iSeriesCount[0] variable of the ForEachSeries tag iSeriesPosition[0] variable of the ForEachSeries tag

About variables for chart coordinates


The ForEachDatapoint, ForEachLegend, and ForEachSeries tags have variables that contain a string of numbers representing the coordinates for the polygon around the edge of a chart element. These variables are called strDatapointCoordinates, strLegendCoordinates, and strSeriesCoordinates, respectively. The JSP Charting API outputs these values so that web designers can use them to create image maps for the given chart area. The values are output in the order that the coords attribute of the HTML <area> tag requires.

About the taglib directive


Each JSP page that contains a JSP Charting API tag must also contain a statement indicating which tag library these tags belong to and the prefix for the tags. This statement is called the taglib directive.

Structure of the taglib directive


The taglib directive is a line in a JSP file that looks like this:
<%@ taglib uri="taglib_name" prefix="myprefix" %>

Chapter 17, Converting e.Spreadsheet data to HTML

377

This table describes each part of the taglib directive. Taglib directive part <%@ ... %> Description The % signs indicate that this is JSP code. The @ sign indicates that this is a directive. Directives are processed before all other code on a JSP page. This indicates that this JSP page uses custom tags from a tag library. This indicates that the following name is a Universal Resource Identifier for pointing to the JSP Charting API TLD file. For more information, see The URI in the taglib directive, later in this chapterThe URI in the taglib directive. A name established when you installed JSP Charting API that points to the JSP Charting API TLD file. You must enter the exact name (with matching case) that was created for the URI during the installation. For more information, see The URI in the taglib directive, later in this chapterThe URI in the taglib directive. This indicates that the following string will always prefix the JSP Charting API tags that you use on this page. If the page uses custom tags from more than one tag library, this prefix tells the JSP engine which tag library contains the code for this tag. This is any string you want to use to indicate that the following tag comes from the JSP Charting API tag library. All of the examples in the documentation use the prefix f1.

taglib uri

taglib_name

prefix

myprefix

Where to put the taglib directive


The taglib directive must appear on the JSP page before the first use of any JSP Charting API tags. In the examples, the taglib directive is the first line in the JSP code.

The URI in the taglib directive


Your taglib directive contains a name for a URI. That URI was created in the configuration files of the web server where you installed the JSP Charting API. The URI points to the JSP Charting APIs TLD file, which defines the JSP Charting API tags and associated attributes.

378

Programming e.Spreadsheet Reports

The taglib directive must contain the exact spelling and case of the URI created when the JSP Charting API was installed on your web server. Since each installation of the JSP Charting API is different, this documentation cant tell you what the URI for your installation should be. However, the table below shows which file or files should contain the XML element that defines the URI. The table also gives a reference for further information. Web server JRun JRun Install type individual shared File that defines the taglib directive URI [root of web application]/WEB-INF/web.xml [jrun install directory]/servers/[server name]/ local.properties or [jrun install directory]/lib/global.properties [root of web application]/WEB-INF/web.xml [tomcat install directory]/conf/web.xml or [root of web application]/WEB-INF/web.xml

TomCat TomCat

individual shared

JSP Charting API examples by tag


The JSP Charting APIs examples can be accessed online from the test page of the test web app. Each example is documented online. This table lists the examples in the leftmost column and the JSP Charting API tags along the top. The Xs in the table show which tags are used in each example. CreateDataQuery CreateDataRange CreateFileDataSource CreateJDBCDataSource ForEachDatapoint ForEachLegend ForEachSeries GetBook GetCell GetChart GetRange InsertCell InsertChart InsertChartImageMap InsertDebug InsertRange InsertVersion LoadBook RefreshData SetCell SetDataQueryParameter SetRange UnloadBook x x x x x
Chapter 17, Converting e.Spreadsheet data to HTML

# 1

Description Using InsertChart to display different sizes of PNG images

379

# 2

Description Using ForEachSeries and ForEachDatapoint to build an imagemap Using InsertChartImageMap to create an imagemap Using a custom .class to encode an LZWcompressed GIF Using InsertChartImageMap with a custom XSLT document to create an imagemap Using XSLT to format a table Merging two ranges of data with InsertRange Using GetRange to build a table

6 7

380

Programming e.Spreadsheet Reports

CreateDataQuery CreateDataRange CreateFileDataSource CreateJDBCDataSource ForEachDatapoint ForEachLegend ForEachSeries GetBook GetCell GetChart GetRange InsertCell InsertChart InsertChartImageMap InsertDebug InsertRange InsertVersion LoadBook RefreshData SetCell SetDataQueryParameter SetRange UnloadBook x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x

# 9

Description Using InsertRange to translate a worksheet into a custom XML document via XSLT

10 Creating a data source in an Excel document 11 Loading a workbook via a URL

x x x x

12 Remapping an XML DataSource and associated DataRanges XSLT document 13 Remapping a JDBC DataSource to a JNDI name 14 Creating a new book x

CreateDataQuery CreateDataRange CreateFileDataSource CreateJDBCDataSource ForEachDatapoint ForEachLegend ForEachSeries GetBook GetCell GetChart GetRange InsertCell InsertChart InsertChartImageMap InsertDebug InsertRange InsertVersion LoadBook RefreshData SetCell SetDataQueryParameter SetRange UnloadBook x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x
Chapter 17, Converting e.Spreadsheet data to HTML

381

Tag reference
This section contains an alphabetical reference for all JSP Charting API tags. Required tag attributes appear in boldface type. For information about the structure and use of tags, attributes, and variables, see Using tags earlier in this chapter.Using tags.

CreateDataQuery
Creates a DataQuery in the specified JDBC DataSource. You may nest this tag within opening and closing CreateJDBCDataSource tags. You may set the parameter(s) specified in this query by later using the SetDataQueryParameter tag. Syntax
<f1:CreateDataQuery . . ./>

Attributes book The name of the workbook in which to create the DataSource. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. If this tag is nested, the parent tags book value is used, so you can omit this attribute. A name you give this data query. The name of the DataSource this query applies to. In the Workbook Designer, you can find the names of all of the workbooks DataSources by choosing DataData Manager. If this tag is nested, the parent tags datasource value is used, so you can omit this attribute. The query string to be passed to the database. The query string should be a standard SQL query that your database can understand. If you want to use a stored procedure from the database as your query, enter the name of the stored procedure and set storedprocedure to true. The type of database data: jdbc, xml, or text. You would choose xml or text only if the XML or text were stored in a field of a database record. Defaults to jdbc.

dataquery datasource

query

result

382

Programming e.Spreadsheet Reports

storedprocedure

Enter true if you want the query to execute one of the databases stored procedures. Enter false if the query is not a stored procedure. Defaults to false. If this DataSource has already been created in the workbook, this is the action you want to perform on the existing DataSource. The valid entries are: s delete to remove the existing DataSource and create a new one from scratch. s modify to keep the existing DataSource, changing only the attributes you specify in this tag. s nochange to keep the existing DataSource with no changes. This is the default.

action

Enter values for the following four attributes only if the result attribute has a value of text. Otherwise, these attribute values are ignored. characterdelimiter For character-delimited data, this is the delimiter. You can specify multiple delimiters by entering a string: "\ t,;" specifies the tab character, a comma, and a semicolon as delimiters. Defaults to the tab character. For position-delimited data, these are the numerical column positions, separated by semicolons. If you are using an XSLT document to format the external data, and if that XSLT document requires column names that are different from the default, enter a semicolon-separated list of the column names required by the XSLT document. The first row of the text file you want to import. Use this attribute to truncate title and heading rows from the external data. Defaults to 1.

columnpositions columnnames

startrow

Examples That Use This Tag 10, Creating a DataSource in an Excel document

CreateDataRange
Creates a DataRange for bringing data into the specified workbook. Before creating a DataRange, you must create or specify a DataSource, which defines the type of data that will be brought in. If that DataSource is a database, you must also create a DataQuery to specify which data from the database you

Chapter 17, Converting e.Spreadsheet data to HTML

383

want to bring in. You may nest this tag within opening and closing CreateFileDataSource or CreateDataQuery tags. Syntax
<f1:CreateDataRange . . . />

Attributes book The name of the workbook in which to create the DataRange. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. If this tag is nested, the parent tags book value is used, so you can omit this attribute. The name for the new DataRange. The name of the DataSource that this DataRange uses. In the Workbook Designer, you can find the names of all of the workbooks DataSources by choosing DataData Manager. If this tag is nested, the parent tags datasource value is used, so you can omit this attribute. A reference to the cell in the upper left corner of the range where you want the imported data to appear in the worksheet. Can be a defined name or a cell reference. If the DataSource specified in the datasource attribute is a JDBC database, enter the name of the DataQuery that specifies the data that you want to bring in. In the Workbook Designer, you can find the names of all of the workbooks DataQueries by choosing DataData Manager. If the DataSource is file-based, you do not have to enter this attribute. If this tag is nested, the parent tags dataquery value is used, so you can omit this attribute. Defaults to true to refresh this DataRange at the time it is created. Enter false if you want to refresh the data later, using the RefreshData tag. If this DataSource has already been created in the workbook, this is the action you want to perform on the existing DataSource. The valid entries are: s delete to remove the existing DataSource and create a new one from scratch. s modify to keep the existing DataSource, changing only the attributes you specify in this tag. s nochange to keep the existing DataSource with no changes. This is the default.

datarange datasource

range

dataquery

refresh

action

384

Programming e.Spreadsheet Reports

formatmode

Indicates how incoming data should be formatted. The valid entries are: s clear to remove any existing workbook formatting. s preserve for preserving the existing workbook formatting. This is the default. s replicate to copy down the formatting from the top row of the DataRange into all the lower rows. s xml to use the formatting embedded in the incoming XML document. s xslt to use an XSLT document for formatting. If the formatmode attribute is set to xslt, enter the URL to the XSLT document. Enter true to copy down any formula located in the column immediately to the right of this range into each row retrieved. Defaults to false to not copy any data outside of this DataRange. Enter true to include row numbers in the DataRange. Defaults to false to leave row numbers out of the DataRange. Indicates how surrounding data is treated when the DataRange is inserted into an existing worksheet. Valid entries are: s insertclear to insert entire rows when the range expands and clear unused cells when the range shrinks. s insertdelete to insert cells when the range expands and delete unused cells when the range shrinks. This is the default. s overwriteclear to overwrite existing cells when the range expands and clear unused cells when the range shrinks.

xslt filldown

rownumbers

insertmode

Enter values for the following two attributes only if the result attribute has a value of JDBC. fieldnames Enter true to include JDBC field names in the DataRange. Defaults to false to leave field names out.

Examples That Use This Tag 10, Creating a DataSource in an Excel document

Chapter 17, Converting e.Spreadsheet data to HTML

385

CreateFileDataSource
Creates a DataSource to allow you to bring data into the specified workbook from a text or XML file. To bring data into a workbook from a JDBC database, use the CreateJDBCDataSource tag. Syntax
<f1:CreateFileDataSource . . . />

Attributes book The name of the workbook in which to create the DataSource. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. A name you give to this DataSource. The file name or URL of the XML or text file to bring in. The expected results of the query. The valid entries are xml or text. Defaults to text. If this DataSource has already been created in the workbook, this is the action you want to perform on the existing DataSource. The valid entries are: s delete to remove the existing DataSource and create a new one from scratch. s modify to keep the existing DataSource, changing only the attributes you specify in this tag. s nochange to keep the existing DataSource with no changes. This is the default. For character-delimited data, this is the delimiter. You can specify multiple delimiters by entering a string: "\ t,;" specifies the tab character, a comma, and a semicolon as delimiters. Defaults to the tab character. If the external file is position-delimited text, these are the column positions to be used, separated by semicolons (e.g. 4;10;15;23;45) If you are using an XSLT document to format the external data, and if that XSLT document requires column names that are different from the default, enter a semicolon-separated list of the column names required by the XSLT document.

datasource file result action

characterdelimiter

columnpositions

columnnames

386

Programming e.Spreadsheet Reports

startrow

If the external file is text, this specifies the starting row to use when populating the workbook. Use this attribute to truncate title and heading rows from the external data. Defaults to 1.

Examples That Use This Tag 10, Creating a DataSource in an Excel document

CreateJDBCDataSource
Creates a DataSource to allow you to bring data into the specified workbook from a JDBC-compliant database. To bring a text or XML file into a workbook, use the CreateFileDataSource tag. Syntax
<f1:CreateJDBCDataSource . . . />

Attributes book The name of the workbook in which to create the DataSource. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. A name you give this DataSource. The name of the JDBC driver to be used to connect the DataSource to the database. The database connection string used to specify which database the driver is to connect. The user login name for the database. Some databases may not require you to enter a username and password. The JDBC password corresponding to the user name. Some databases may not require you to enter a username and password. If you have created a JNDI connection to the database, enter its fully qualified name, as specified in the web server. The name might look like this: java:/comp/env/jdbc/ yourdatabaseconnectionname. If you enter a value for this attribute, you dont have to enter values for the driver, database, user, or password attributes.

datasource driver database user password

jndi

Chapter 17, Converting e.Spreadsheet data to HTML

387

action

If this DataSource has already been created in the workbook, this is the action you want to perform on the existing DataSource. The valid entries are: s delete to remove the existing DataSource and create a new one from scratch. s modify to keep the existing DataSource, changing only the attributes you specify in this tag. s nochange to keep the existing DataSource with no changes. This is the default.

Examples That Use This Tag 10, Creating a DataSource in an Excel document

ForEachDatapoint
Sets up an iteration over data points within the current series. This tag must be enclosed within ForEachSeries beginning and ending tags. Syntax
<f1:ForEachDatapoint> ... </f1:ForEachDatapoint>

Variables String strDatapointName The name of the category the data point belongs to. The name is updated each time the loop is executed. The number of data points in the current series. The current position of the iteration. This number is incremented each time the loop is executed. A list of the (x,y) values for the polygon that circumscribes this data point. These values can be used when creating an image map for this data point. The coordinates are updated each time the loop is executed. The data points value. The value is updated each time the loop is executed.

int iDatapointCount[0] int iDatapointPosition[0]

String strDatapointCoordinates

String strDatapointValue Examples That Use This Tag

2, Using ForEachSeries and ForEachDatapoint to build an imagemap

388

Programming e.Spreadsheet Reports

ForEachLegend
Sets up an iteration over the legend items in a chart. This tag must be enclosed within GetChart beginning and ending tags. Syntax
<f1:ForEachLegend> ... </f1:ForEachLegend>

Variables String strLegendName The text of the current legend item. The name is updated each time the loop is executed. The number of legend items. The current position of the iteration. This number is incremented each time the loop is executed. A list of the (x,y) values for the polygon that circumscribes the legend item. These values can be used when creating an image map area for this legend item. The coordinates are updated each time the loop is executed.

int iLegendCount[0] int iLegendPosition[0]

String strLegendCoordinates

Examples That Use This Tag 2, Using ForEachSeries and ForEachDatapoint to build an imagemap

ForEachSeries
Sets up an iteration over each series within the specified chart. This tag must be enclosed within GetChart beginning and ending tags. Syntax
<f1:ForEachSeries> ... </f1:ForEachSeries>

Variables String strSeriesName int iSeriesCount[0] int iSeriesPosition[0] The name of the current series. The name is updated each time the loop is executed. The number of series. The current position of this iteration. This number is incremented each time the loop is executed.

Chapter 17, Converting e.Spreadsheet data to HTML

389

String strSeriesCoordinates

A list of (x,y) values for the polygon that encloses this series. These values can be used when creating an image map area for this series. The coordinates are updated each time the loop is executed.

Examples That Use This Tag 2, Using ForEachSeries and ForEachDatapoint to build an imagemap

GetBook
Retrieves the books data (in VTS format) into a JSP variable. You can use this tag to save modified workbooks to disk or offline storage. Syntax
<f1:GetBook . . .> ... </f1:GetBook>

Attribute book The name of the workbook. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. A byte array containing the workbook data.

Variable byBookData[] Examples That Use This Tag 14, Creating a new book

GetCell
Retrieves the cell text, formula, or value into a JSP variable. Syntax
<f1:GetCell . . . > ... </f1:GetCell>

Attributes book The name of the workbook containing the cell. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook.

390

Programming e.Spreadsheet Reports

cell text formula value Variables

The workbook cell. This can be a defined name or a cell reference. Defaults to true to populate the strGetCellText variable. Enter false to not populate that variable. Enter true to populate the strGetCellFormula variable. Defaults to false to not populate that variable. Enter true to populate the dGetCellValue variable. Defaults to false to not populate that variable. The text contained in the cell. If the cell contains a formula, this variable returns the result of that formula. If the cell is empty, this variable returns "". If the cell has a number format applied, this variable returns the formatted number. The formula contained in the cell. If the cell is empty or does not contain a formula, this variable returns "". The value contained in the cell. If the cell contains a formula, this variable returns the result of that formula. If the cell is empty or contains text, this variable returns 0 (zero).

String strGetCellText

String strGetCellFormula

double dGetCellValue[0]

Examples That Use This Tag 11, Loading a workbook via a URL

GetChart
Prepares a chart for inclusion into an HTML page and places the URL to a servlet that creates the specified chart in the variable strGetChartURL. Syntax
<f1:GetChart . . . > ... </f1:GetChart>

Attributes book The name of the workbook containing the chart. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook.

Chapter 17, Converting e.Spreadsheet data to HTML

391

chart

The name of the chart. In the Workbook Designer, you can find the charts name by selecting the chart, selecting FormatObjectOptions, and looking for the value in the Name tab of the resulting Format Object dialog. This sets the width of the chart, in pixels. If you do not set this attribute, the original width of the chart is used. The exception is when aspect is true and the height attribute is set, in which case the chart width is sized proportionally. See About chart sizing attributes, later in this chapter,About chart sizing attributes for examples of how the width attribute works. This sets the height of the chart, in pixels. If you do not set this attribute, the original height of the chart is used. The exception is when aspect is true and the width attribute is set, in which case the chart height is sized proportionally. See About chart sizing attributes, later in this chapter,About chart sizing attributes for examples of how the height attribute works. Defaults to true to preserve ratio of the charts width to its height. In this case, if either the width or the height attribute is set, the chart is scaled to match that width or height. If both the width and height attributes are set, the setting that maximizes the charts size will be used and the other setting will be disregarded. Enter false to change the ratio of width to height. If only the width attribute is set, the charts original height is used. If only the height attribute is set, the charts original width is used. If both the width and height attributes are set, both are used. If neither the width or height attribute is set, the charts aspect ratio is preserved. See About chart sizing attributes, later in this chapter,About chart sizing attributes for examples of how the aspect attribute works. This sets the size of the charts internal elements: text, patterns, line widths, etc. Enter the percentage of the charts original size that you want the charts internal elements to appear in. (For example, enter a value of 200 for text twice as large as the original.) This attribute has no effect on the size of the chart. See About chart sizing attributes, later in this chapter,About chart sizing attributes for examples of how the scale attribute works.

width

height

aspect

scale

392

Programming e.Spreadsheet Reports

type

The type of encoding: gif, rlegif, or png. Defaults to rlegif. For special information about GIF images, see About charts encoded as GIF images, later in this chapterAbout charts encoded as GIF images. To change the Java class that generates images from charts, enter the name of the Java class. The class must be found on the servers path and must implement the com.f1j.swing.ImageCompressionIF interface. In this case, the type of image encoded is defined by the method getMimeType() of the ImageEncoderIF interface. For more information about creating classes that write chart objects as images, see Chapter 10, Input/Output, in Programming e.Spreadsheet ReportsChapter 10, Input/Output, in Programming e.Spreadsheet Reports. If you want to change the data range that the chart is based on, enter the new range reference. This attribute is most useful for charts linked to DataRanges, which are based on external data. The size or shape of the chart data range may change when the external data is refreshed.

range

The following attribute should be used only if you set a value for the range attribute. seriesinrows Enter true to build a chart using the new ranges rows as the chart series. Enter false to use the columns as the chart series. The default is the setting on the original chart, before you change the data range. The URL to the servlet that creates the chart. To place an image of the chart drawn on a JSP page, use this URL as the value of the src attribute in an HTML <img> tag. A list of the (x,y) values for the polygon that makes up the outside frame of the chart, separated by commas. These values can be used when creating an image map area for the chart.

Variables String strGetChartURL

String strGetChartCoordinates

Examples That Use This Tag 2, Using ForEachSeries and ForEachDatapoint to build an imagemap 3, Using InsertChartImageMap to create an imagemap 5, Using InsertChartImageMap with a custom XSLT document to create an imagemap

Chapter 17, Converting e.Spreadsheet data to HTML

393

About charts encoded as GIF images


When you assign the value gif to the type attribute of the GetChart and InsertChart tag, what you get is not a true GIF image. The technology to create GIFs is patented and therefore unavailable to the JSP Charting API. However, if you have a license to create true GIF images, you can create them by using a GIF encoder. For information on how to do this, see example 4, Using a custom .class to encode an LZW-compressed GIF. PNG is generally the best option for chart images in web development, as long as users browsers support the PNG format. This is because the image files are usually small and because, unlike GIFs, there is no licensing issue involved in using PNGs.

About chart sizing attributes


The GetChart and InsertChart tags have four attributes that establish the size and look of the chart on the HTML page. They are width, height, aspect, and scale. The attributes depend on one another, so that if you change one attributes value, a different attribute might be affected. The table below displays each combination of chart sizing attributes for the default chart shown in the top table row. The charts on the left all have the aspect attribute set to true (the default), while the charts on the right have aspect set to false. You can see that setting the aspect attribute to false has no effect unless the height and/or width attributes are also set. Also, the scale

394

Programming e.Spreadsheet Reports

attribute affects only the size of elements within the chart, not the size of the chart itself. aspect="true" (default) Example 1 no attributes but aspect set aspect="false"

This is the default chart with no sizing attributes. Example 2 width="125" When aspect is true, both width and height change proportionally when you change width only.

Setting aspect to false has no effect unless width or height is also set.

When aspect is false, the height of the original chart is maintained when you change the width.

Example 3 height="100"

When aspect is true, both width and height change proportionally when you change the height only. Example 4 scale="50"

When aspect is false, the width of the original chart is maintained when you change the height.

The scale attribute doesnt change the size of the chart (see example 1), just the size of chart internals such as text and patterns.

The aspect attribute setting has no effect when only the scale attribute is set (see example 1).

Chapter 17, Converting e.Spreadsheet data to HTML

395

aspect="true" (default) Example 5 width="125" height="100" When aspect is true, either width or height is disregarded when sizing the chart. Example 6 width="125" scale="50" The chart size is the same as when just width was set (see example 2), but the text and pattern have been scaled down.

aspect="false"

When aspect is false, both the width and height settings apply.

The chart size is the same as when just width was set (see example 2), but the text and pattern have been scaled down.

Example 7 height="100" scale="50" The chart size is the same as when just height was set (see example 3), but the text and pattern have been scaled down. Example 8 width="125" height="100" scale="50" The chart size is the same as when just width and height apply (see example 5), but the text and pattern have been scaled down. The chart size is the same as when just width and height apply (see example 5), but the text and pattern have been scaled down. The chart size is the same as when just width was set (see example 2), but the text and pattern have been scaled down.

396

Programming e.Spreadsheet Reports

GetRange
Retrieves the cell values into a two- or three-dimensional JSP variable. Syntax
<f1:GetRange . . . > ... </f1:GetRange>

Attributes book The name of the workbook containing the range. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The name of the requested range. This can be a defined name or a cell or range reference. Defaults to true to populate the strGetRangeText2[][] or strGetRangeText3[][][] variable. Enter false to not populate those variables. Enter true to populate the strGetRangeFormula2[][] or strGetRangeFormula3[][][] variable. Defaults to false to not populate those variables. Enter true to populate the dGetRangeValue2[][] or dGetRangeValue3[][][] variable. Defaults to false to not populate those variables. A two-dimensional array consisting of the formatted text in the specified rows and columns on the specified sheet. Numbers in cells appear in the array as text strings. Empty cells appear in the array as "". A three-dimensional array consisting of the formatted text in the specified rows and columns on all of the specified worksheets. Numbers in cells appear in the array as text strings. Empty cells appear in the array as "". This variable is populated only if the range refers to cells on two or more worksheets.

range text

formula

value

Variables String strGetRangeText2[][]

String strGetRangeText3[][][]

Chapter 17, Converting e.Spreadsheet data to HTML

397

String strGetRangeFormula2[][]

A two-dimensional array consisting of the formulas in the specified rows and columns on the specified sheet. Empty cells and cells that do not contain a formula appear in the array as "". A three-dimensional array consisting of the formulas in the specified rows and columns on all of the specified sheets. Empty cells and cells that do not contain a formula appear in the array as "". This variable is populated only if the range refers to cells on two or more worksheets. A two-dimensional array consisting of the values in the specified rows and columns on the specified sheet. Empty cells and cells that contain text appear in the array as "". A three-dimensional array consisting of the values in the specified rows and columns on all of the specified sheets. Empty cells and cells that contain text appear in the array as "". This variable is populated only if the range refers to cells on two or more worksheets. The number of sheets in the range. The number of rows in the range. The number of columns in the range.

String strGetRangeFormula3[][][]

Double dGetRangeValue2[][]

Double dGetRangeValue3[][][]

int iGetRangeSheetCount[0] int iGetRangeRowCount[0] int iGetRangeColumnCount[0] Examples That Use This Tag 8, Using GetRange to build a table

InsertCell
Inserts the contents of the specified cell from the specified workbook into the HTML page. If the cell has a number format applied, this tag returns the formatted number. Syntax
<f1:InsertCell . . . />

398

Programming e.Spreadsheet Reports

Attributes book The name of the workbook containing the cell. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The workbook cell. This can be a defined name or a cell reference.

cell

Examples That Use This Tag 11, Loading a workbook via a URL

InsertChart
Inserts a chart (and an imagemap, if requested) into the HTML page by creating an <img> tag with the F1TagLibImageServlet as its source. This tag combines the functionality found in the GetChart and InsertChartImageMap tags. Syntax
<f1:InsertChart . . . />

Attributes book The name of the workbook containing the chart. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The name of the chart. In the Workbook Designer, you can find the charts name by selecting the chart, selecting FormatObjectOptions, and looking for the value in the Name tab of the resulting Format Object dialog. This sets the width of the chart, in pixels. If you do not set this attribute, the original width of the chart is used. The exception is when aspect is true and the height attribute is set, in which case the chart width is sized proportionally. See About chart sizing attributes, earlier in this chapter,About chart sizing attributes for examples of how the width attribute works. This sets the height of the chart, in pixels. If you do not set this attribute, the original height of the chart is used. The exception is when aspect is true and the width attribute is set, in which case the chart height is sized proportionally. See About chart sizing attributes, earlier in this chapter,About chart sizing attributes for examples of how the height attribute works.

chart

width

height

Chapter 17, Converting e.Spreadsheet data to HTML

399

aspect

Defaults to true to preserve ratio of the charts width to its height. In this case, if either the width or the height attribute is set, the chart is scaled to match that width or height. If both the width and height attributes are set, the setting that maximizes the charts size will be used and the other setting will be disregarded. Enter false to change the ratio of width to height. If only the width attribute is set, the charts original height is used. If only the height attribute is set, the charts original width is used. If both the width and height attributes are set, both are used. If neither the width or height attribute is set, the charts aspect ratio is preserved. See About chart sizing attributes, earlier in this chapter,About chart sizing attributes for examples of how the aspect attribute works. This sets the size of the charts internal elements: text, patterns, line widths, etc. Enter the percentage of the charts original size that you want the charts internal elements to appear in. (For example, enter a value of 200 for text twice as large as the original.) This attribute has no effect on the size of the chart. See About chart sizing attributes, earlier in this chapter,About chart sizing attributes for examples of how the scale attribute works. The type of encoding: gif, rlegif, or png. Defaults to rlegif. For special information about GIF images, see About charts encoded as GIF images, earlier in this chapterAbout charts encoded as GIF images. To change the Java class that generates images from charts, enter the name of the Java class. The class must be found on the servers path and must implement the com.f1j.swing.ImageCompressionIF interface. In this case, the type of image encoded is defined by the method getMimeType() of the ImageEncoderIF interface. For more information about creating classes that write chart objects as images, see Chapter 10, Input/Output, in Programming e.Spreadsheet ReportsChapter 10, Input/Output, in Programming e.Spreadsheet Reports. If you want to change the data range that the chart is based on, enter the new range reference.

scale

type

range

400

Programming e.Spreadsheet Reports

seriesinrows

You should enter a value for this attribute only if you set a value for the range attribute. Enter true to build a chart using the new ranges rows as the chart series. Enter false to use the columns as the chart series. The default is the setting on the original chart, before you change the data range. The name of the image map you want the tag to create. The default URL for each <area> element in the image map. This value is passed to the XSLT processor via the ChartMap XML data stream. The default URL for each data point <area> element in the image map. This overrides the url attribute. The default URL for each series <area> element in the image map. This overrides the url attribute. The default URL for each legend <area> element in the image map. This overrides the url attribute. The name or URL to the XSLT document to use when converting from ChartMap XML to HTML image map syntax. If not specified, it defaults to the default internal XSLT document.

chartmap url

datapointurl seriesurl legendurl xslt

The following three attributes should be used only if you are using the default XSLT document. datapoint Defaults to true to make each data point a clickable area on the chart map. Enter false to leave the data points off the map. Defaults to true to make each series a clickable area on the chart map. Enter false to leave the series off the map. Defaults to true to make each legend item a clickable area on the chart map. Enter false to leave the legend items off the map.

series legend

Examples That Use This Tag 1, Using InsertChart to display different sizes of PNG images 4, Using a custom .class to encode an LZW-compressed GIF

InsertChartImageMap
Creates an imagemap based on the generated chart and inserts it into the HTML page. This tag must be enclosed in GetChart tags. Syntax
<f1:InsertChartImageMap . . . />

Chapter 17, Converting e.Spreadsheet data to HTML

401

Attributes chartmap url The name of the image map you want the tag to create. The default URL for each <area> element in the image map. This value is passed to the XSLT processor via the ChartMap XML data stream. The default URL for each data point <area> element in the image map. This overrides the url attribute. The default URL for each series <area> element in the image map. This overrides the url attribute. The default URL for each legend <area> element in the image map. This overrides the url attribute. The name or URL to the XSLT document to use when converting from ChartMap XML to HTML image map syntax. If not specified, it defaults to the default XSLT document.

datapointurl seriesurl legendurl xslt

The following three attributes should be used only if you are using the default XSLT document. datapoint Defaults to true to make each data point a clickable area on the chart map. Enter false to leave the data points off the map. Defaults to true to make each series a clickable area on the chart map. Enter false to leave the series off the map. Defaults to true to make each legend item a clickable area on the chart map. Enter false to leave the legend items off the map.

series legend

Examples That Use This Tag 3, Using InsertChartImageMap to create an imagemap 5, Using InsertChartImageMap with a custom XSLT document to create an imagemap

InsertDebug
Inserts a link that pops up a new browser displaying the debug log for this JSP page. This is helpful in tracking down errors in the JSP document. Debug information is not collected unless or until this tag is encountered, so you should place it near the top of your JSP document. You can change the value of a context parameter to control how this tag performs. For more

402

Programming e.Spreadsheet Reports

information, see List of context parameters and their values later in this chapter. List of context parameters and their values. Syntax
<f1:InsertDebug/>

Attributes action Allows you to place the URL that displays the debug log in an HTML comment or hide it completely. The valid entries are: s hide to save the debug URL as a comment in the generated HTML, but show nothing in the browser. s ignore to completely remove the debug URL from the generated HTML s show to display the debug URL in the generated HTML, so that it appears in the browser. This is the default. This attribute overrides the context parameter f1taglib.debug, documented in List of context parameters and their values later in this chapter. List of context parameters and their values. It can be used to temporarily display a debug tag hidden by the context parameter.

Examples That Use This Tag All the examples use this tag.

InsertRange
Inserts a worksheet range into an HTML page. Worksheet rows become HTML table rows and worksheet cells become table data. Syntax
<f1:InsertRange . . . />

Attributes book The name of the workbook containing the range you want to insert. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The name of the cell or range(s) to insert. This can be a defined name or a cell or range reference. You can specify multiple ranges separated by semicolons: "A1;B6;Sales".

range

Chapter 17, Converting e.Spreadsheet data to HTML

403

spreadsheetformat Enter true to pass formats from the worksheet to the XSLT processor. Defaults to false to disregard any formatting on the worksheet. merge Enter true to place multiple ranges specified in the range attribute side by side before the XSLT processing is performed. Defaults to false to place each of the multiple ranges below the first before the XSLT processing is performed. Defaults to true to automatically generate the opening and closing <table> tags. Enter false to create the <table> tags yourself or let the JSP do it. The name or URL of the XSLT document to convert worksheet contents to an HTML table. If you omit this attribute, the system will use a default XSLT document. If you specify an empty string, the system outputs the XML which would have been passed to the XSLT processor.

table

xslt

The following attribute should be used only if you entered a value for the xslt attribute. cellkeys A cells keys are all the defined names that apply to that cell. When the InsertRange tag pulls data out of a workbook, it can optionally include cell key data in the temporary XML document it creates from the workbook data. Enter true if your custom XSLT document requires that temporary XML document to contain cell key data. Defaults to false to not include cell key data in the temporary XML.

Examples That Use This Tag 6, Using XSLT to format a table 7, Merging two ranges of data with InsertRange 9, Using InsertRange to translate a worksheet into a custom XML document via XSLT 10, Creating a DataSource in an Excel document 11, Loading a workbook via a URL 12, Remapping an XML DataSource and associated DataRanges XSLT document 13, Remapping a JDBC DataSource to a JNDI name

404

Programming e.Spreadsheet Reports

InsertVersion
Inserts a text string indicating which version of the JSP Charting API is being used. Syntax
<f1:InsertVersion/>

Examples That Use This Tag 14, Creating a new book

LoadBook
Loads a workbook into memory. You must use this tag to load a book before you use any tag that refers to that book. Workbooks loaded using LoadBook persist throughout the browser session, so you only have to call LoadBook in the first JSP page that refers to it. To remove a workbook from memory, use UnloadBook. Syntax
<f1:LoadBook . . . />

Attributes book source A name you choose for this workbook in the current browser session. This is the name you enter in other tags book attribute. The source for this book. It can be the name and path to an existing VTS or XLS file, a name whose value you set in the properties file, or you can create an empty book by setting this variable equal to an empty string (""). If you enter a value for the data attribute, you shouldnt enter a value for source, unless you want to map the value in the properties file. A byte array containing data for the book. You enter the name of the byte array as part of a JSP expression, which might look something like this: data=<%=bytearray%>. If you enter a value for data, you dont need to enter a value for source. This attribute controls whether subsequent uses of LoadBook for the same source use the copy of the workbook thats cached in the browser session or re-open the original workbook file. Enter true to reload the workbook from the original file. Enter false to use the copy of the workbook thats cached in the browser session. Defaults to false.

data

reload

Examples That Use This Tag All the examples use this tag.

Chapter 17, Converting e.Spreadsheet data to HTML

405

RefreshData
Refreshes the external data in a workbook. You have three options: refresh all external data from all DataSources, refresh all external data from one DataSource, or refresh one DataQuery linked to one DataSource. Syntax
<f1:RefreshData . . . />

Attributes book The name of the workbook containing the external data you want to refresh. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The name of a specific DataSource you want to refresh. If you dont enter a value, it will refresh all external data in the workbook. In the Workbook Designer, you can find the names of the workbooks DataSources by choosing DataData Manager. The name of a specific DataQuery you want to refresh. This DataQuery must be linked to the DataSource you specified in the datasource attribute. If you dont enter a value for dataquery, it will refresh all DataQueries linked to this DataSource. In the Workbook Designer, you can find the names of the workbooks DataQueries by choosing DataData Manager.

datasource

dataquery

Examples That Use This Tag 1, Using InsertChart to display different sizes of PNG images 6, Using XSLT to format a table 7, Merging two ranges of data with InsertRange 8, Using GetRange to build a table 9, Using InsertRange to translate a worksheet into a custom XML document via XSLT 10, Creating a DataSource in an Excel document 11, Loading a workbook via a URL 12, Remapping an XML DataSource and associated DataRanges XSLT document 13, Remapping a JDBC DataSource to a JNDI name

406

Programming e.Spreadsheet Reports

SetCell
Puts a specified value or formula into a worksheet cell. If you specify more than one cell, all cells will be populated with the same value or formula. Syntax
<f1:SetCell . . . />

Attributes book The name of the workbook containing the cell you want to populate. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The name of the cell. This can be a defined name or a cell reference. You can specify multiple cells separated by semicolons: "A1;B6;Sales". The text, value, or formula to put into the cell. To place a formula in the cell, precede the formula with an = sign (Excel syntax).

cell

entry

Examples That Use This Tag 11, Loading a workbook via a URL

SetDataQueryParameter
Allows you to set the values for database query parameters before the DataRange is refreshed. Syntax
<f1:SetDataQueryParameter . . . />

Attributes book The name of the workbook containing the external database data that you want to parameterize. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The name of the data query. In the Workbook Designer, you can find the names of all of the workbooks DataQueries by choosing DataData Manager. The name of the DataSource that this parameter applies to. In the Workbook Designer, you can find the names of all of the workbooks DataSources by choosing DataData Manager.

dataquery

datasource

Chapter 17, Converting e.Spreadsheet data to HTML

407

entry

The query parameter itself, in the form of a value or cell reference. The data must conform to the requirements of the query and the type specified in the type attribute. The type of data of the parameter: int, char, float, or double. Defaults to char. This indicates which parameter you are setting. This attribute is zero-based, so enter 0 for parameter 1, 1 for parameter 2, etc. Defaults to 0 (zero).

type index

Examples That Use This Tag 11, Loading a workbook via a URL

SetRange
Puts a specified value or formula into a worksheet range. All cells in the range will be populated with the same value or formula. Syntax
<f1:SetRange . . . />

Attributes book The name of the workbook containing the range you want to set. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook. The name of the range. This can be a defined name or a range reference. You can specify multiple ranges separated by semicolons: "A1:B6;Sales". The text, value, or formula to put into each cell in the range. To place a formula, precede the formula with an = sign (Excel syntax).

range

entry

Examples That Use This Tag 14, Creating a new book

UnloadBook
Removes a workbook from the servers memory. This tag should be used at the discretion of the web developer. You can choose never to unload a book, or you can unload each book. If you are having problems running out of memory, adding UnloadBook tags to your JSPs may help alleviate the problem. If

408

Programming e.Spreadsheet Reports

youve used LoadBook multiple times for the same book, you need to call UnloadBook that same number of times to fully remove the workbook. Syntax
<f1:UnloadBook . . . />

Attributes book The name of the workbook you want to remove from memory. You can only use workbooks that have been loaded into the current browser session using LoadBook. The name you enter must match the name in the book attribute of LoadBook.

Examples That Use This Tag All the examples use this tag.

Using the properties file


The JSP Charting API allows each web application to specify one properties file that allows you to use the tags more efficiently. This properties file is used to: 1 Change the default attribute values. For information, see Changing default attribute values, later in this chapterChanging default attribute values. 2 Override tag attribute values specified on JSP pages. For information, see Overriding attribute values, later in this chapterOverriding attribute values. 3 Redefine/map attribute values. For information, see Redefining attribute values, later in this chapterRedefining attribute values. The main advantages to using a properties file are:
s

Isolation of physical file names, URLs, etc. from the names used in the JSP. By using the properties file, you retain the flexibility to rename and move the worksheet files/defined names, etc. without affecting the JSP code. Overriding attribute values allows you to make global changes to existing JSP pages with specified tag attributes in one location. For example, just one entry in the properties file allows you to change all of the image output types from whatever was specified in the JSP to PNG or GIF.

Your web server has properties files of its own, which are used to configure the servers settings. In this documentation, when we refer to the properties file, we refer to the JSP Charting API properties file.

Chapter 17, Converting e.Spreadsheet data to HTML

409

Structure of the properties file


The properties file is a text file. It requires no special title or heading. The following is an example of a properties file with only two entries:
f1taglib.source.default=/examples/data/example.vts f1taglib.source.example=/examples/data/example.vts

Property keys and property values


In each entry, the text to the left of the equals sign is the property key, which identifies which attribute you are working with. The text to the right of the equals sign is the property value, which assigns a value to the identified attribute. For a list of all the property keys that can be used in the properties file, see List of property keys and their tags, later in this chapter.List of property keys and their tags.

Order of entries
You can put your entries in the properties file in any order, although it might be helpful to group entries of different kinds together.

Comments
You can create a comment in the properties file by preceding the line with the # character.

File name
The name of your properties file should be *.properties, with * representing the title of your choice.

Context parameter
The web application specifies the properties file via a servlet context parameter in the applications web.xml file. The context parameter, which is created when you install the JSP Charting API, looks like this:
<context-param> <param-name>F1TagLib.mapfile</param-name> <param-value>/WEB-INF/installtest.properties</param-value> </context-param>

For more information on this context parameter, see the installation instructions in Part 1 of this manual.

410

Programming e.Spreadsheet Reports

Changing default attribute values


Many tag attributes have default values. For example, the InsertRange tags table attribute defaults to true. The following line in the properties file changes that attributes default value to false:
f1taglib.source.*.table.default=false

The * in this example is a wildcard that applies this property to all sources. The following default values can be set for each type of tag. In each entry, all of the possible property values for a particular entry are shown. In actual properties file entries, only one property value should appear.

Defaults for the InsertRange and InsertCell tags


f1taglib.source.*.cellkeys.default=true,false f1taglib.source.*.merge.default=true,false f1taglib.source.*.spreadsheetformat.default=true,false f1taglib.source.*.table.default=true,false

Defaults for the GetRange and GetCell tags


f1taglib.source.*.text.default=true,false f1taglib.source.*.value.default=true,false f1taglib.source.*.formula.default=true,false

Defaults for charting tags


The tags that use these attributes are GetChart, InsertChart, and InsertChartImageMap.
f1taglib.source.*.chart.*.aspect.default=true,false f1taglib.source.*.chart.*.chartmap.default=custom default value f1taglib.source.*.chart.*.datapoint.default=true,false f1taglib.source.*.chart.*.datapointurl.default=custom default value f1taglib.source.*.chart.*.legend.default=true,false f1taglib.source.*.chart.*.legendurl.default=custom default value f1taglib.source.*.chart.*.scale.default=true,false f1taglib.source.*.chart.*.series.default=true,false f1taglib.source.*.chart.*.seriesurl.default=custom default value f1taglib.source.*.chart.*.type.default=gif,png,rlegif,encode class f1taglib.source.*.chart.*.url.default=custom default value

The entries with custom default value after the equals sign have no specified property values to choose from. You need to create your own custom default values. Some of the attributes are used by more than one tag. When specifying these attributes in the properties file, you affect all of the tags that contain that attribute. For information on which tag(s) each attribute applies to, see List of

Chapter 17, Converting e.Spreadsheet data to HTML

411

property keys and their tags, later in this chapter.List of property keys and their tags.

Overriding attribute values


The asterisk (*) has special meaning in the property key. When the asterisk is used at the end of the key (where the .default string was used for changing default attribute values), that properties file entry overrides all specified values of that attribute. For example, the properties file entry
f1taglib.source.*.chart.*.type.*=gif

overrides all type='' attributes in the charting tags to gif. In this example, we used the asterisk not only in the place of the .default string, but also for the source and chart attribute values. If you only want to apply the override to a certain workbook, you would use the name of the book in place of the first asterisk:
f1taglib.source.mybook.chart.*.type.*=gif

There are two cases in which the asterisk does not override an attribute value set in the JSP.
s

Case 1 You may want all but one or two values of an attribute to be overridden. This can be accomplished by specifying a value for the specific attributes which you do not want to override. For example:
f1taglib.source.sales.chart.*.type.*=gif f1taglib.source.sales.chart.mypngchart.type.*=png

In this example, all charts except the one named mypngchart have their type attribute overridden with the value gif. The mypngchart, however, is overridden with the value png. In general, specific values override the wildcard values.
s

Case 2 You may have created a default for the same attribute. If no value for that attribute is entered in the JSP, the default value is used. For example:
f1taglib.source.*.chart.*.type.default=gif f1taglib.source.*.chart.*.type.*=png

If a JSP page does not specify a value for the type attribute, gif is used. If a JSP page specifies any value for the type attribute, png is used.

412

Programming e.Spreadsheet Reports

Redefining attribute values


The most common use of the properties file is to isolate implementation specifics from the JSP writer. Not only does this increase the security of the application, but it allow the administrator to move and/or rename the worksheet files without affecting the JSP. This provides a bridge between the worksheet (Model) and the JSP (View). The types of attributes you can isolate fall into two categories: files and locations (defined names/ranges).

Redefining attribute values for file isolation


Here is a typical tag:
<f1:LoadBook book=b1 source=http://yourcompany.com/ss/budget99.xls>

When the JSP engine loads the book with this LoadBook tag, the tag specifies a user-defined book name (in this case, b1) along with the source attribute (where to get the file in this case, 'http://yourcompany.com/ss/ budget99.xls, a file from a Web site). If this file is relocated or renamed, the JSP will have to be edited. Using the properties file allows you to create a virtual location for this file. In place of the above tag, you could use the following tag:
<f1:LoadBook book=b1 source=b1source>

You would then create the following entry in your properties file:
f1taglib.source.b1source=http://yourcompany.com/ss/budget99.xls

Now, whenever the name or location of ss/budget99.xls changes, you only have to modify the properties file. The following examples show virtual mappings of other files. Example 1 The xslt='myxslt' attribute in the InsertRange tag is redefined to point to / xsltdocs/budget/99.xsl.
f1taglib.source.b1source.xslt.myxslt=/xsltdocs/budget/99.xsl

Example 2 If the source attribute in the LoadBook tag is omitted, the value /ss/ budget01.vts is used.
f1taglib.source.default=/ss/budget01.vts

Example 3

Chapter 17, Converting e.Spreadsheet data to HTML

413

The xslt=myxslt attribute in the tag <f1:InsertChart (any source) chart=monthlycash xslt=myxslt> is mapped to the file /xsltdocs/budget/ 99chart.xsl.
f1taglib.source.*.chart.monthlycash.xslt.myxslt=/xsltdocs/budget/99chart.xsl

All files beginning with / are relative to the web application root directory. Also, the property value can consist of a filename or a URL (http:/ or ftp:/).

Redefining attribute values for location isolation


Defined names inside of a workbook allow you to refer to a group of cells by a user-defined variable or string. The defined names cell reference is changed if the cells are moved. A similar functionality can be achieved using the properties file to isolate worksheet-specific references from the JSP. For example, the properties file entry
f1taglib.source.budget99.range.dept35=Sheet35!A1:K49

allows the InsertRange tag to refer to the output range by the name 'dept35'. When the tag <InsertRange book='b1' range='dept35'> is processed, the cells A1-K49 on Sheet35 will be delivered to the browser. You can also map to worksheet-defined names so that if the names change, only the properties file needs to be modified. For example, the properties file entry
f1taglib.source.budget99.range.dept35=Department35

allows the InsertRange tag to refer to the output range by the name 'dept35'. When the tag <InsertRange book='b1' range='dept35'> is processed, the cells that are pointed to by the workbook-defined name Department35 will be delivered to the browser. The advantage to using this double-indirection is that it isolates changes in the worksheet even more than in the first example. In the first example, if a couple of rows are inserted on Sheet35, the properties file will need to be modified. However, if a couple of rows are inserted on Sheet35, the defined name Department35 will be updated automatically when the file is saved. Thus the properties file (which refers to Department35) does NOT need any modification to remain functional. If, however, the defined name in the worksheet changes to Department3035, then only one change in the properties file is required to retain JSP functionality.

List of property keys and their tags


The following table lists the property keys in alphabetical order and shows which tags each key applies to. To use these property keys, replace <name>

414

Programming e.Spreadsheet Reports

with an actual name, an asterisk, or default. Replace <value> with the property value you want to assign to that property key. Property keys for attributes of data pipes tags (CreateDataQuery, CreateDataRange, CreateFileDataSource, CreateJDBCDataSource, RefreshData, and SetDataQueryParameter) are not listed on this table because those keys should not be used in the properties file. Instead, you should use a special properties file linked to the VTS or XLS file. For more information, see e.Spreadsheet properties file for Data Pipes, later in this chapter.e.Spreadsheet properties file for Data Pipes. Tag(s) that use the key GetCell, InsertCell, SetCell InsertRange GetChart, InsertChart InsertChart, InsertChartImageMap InsertChart, InsertChartImageMap InsertChart, InsertChartImageMap GetChart, InsertChart InsertChart, InsertChartImageMap InsertChart, InsertChartImageMap GetChart, InsertChart GetChart, InsertChart InsertChart, InsertChartImageMap GetChart, InsertChart InsertChart, InsertChartImageMap GetChart, InsertChart InsertChart, InsertChartImageMap GetChart, InsertChart

Property key f1taglib.source.<name>.cell.<name>=<value> f1taglib.source.<name>.cellkeys.<name>=<value> f1taglib.source.<name>.chart.<name>.aspect.<name>=<value> f1taglib.source.<name>.chart.<name>.chartmap.<name>=<value> f1taglib.source.<name>.chart.<name>.datapoint.<name>=<value> f1taglib.source.<name>.chart.<name>.datapointurl.<name>= <value> f1taglib.source.<name>.chart.<name>.height.<name>=<value> f1taglib.source.<name>.chart.<name>.legend.<name>=<value> f1taglib.source.<name>.chart.<name>.legendurl.<name>=<value> f1taglib.source.<name>.chart.<name>.range.<name>=<value> f1taglib.source.<name>.chart.<name>.scale.<name>=<value> f1taglib.source.<name>.chart.<name>.series.<name>=<value> f1taglib.source.<name>.chart.<name>.seriesinrows.<name>= <value> f1taglib.source.<name>.chart.<name>.seriesurl.<name>=<value> f1taglib.source.<name>.chart.<name>.type.<name>=<value> f1taglib.source.<name>.chart.<name>.url.<name>=<value> f1taglib.source.<name>.chart.<name>.width.<name>=<value>

Chapter 17, Converting e.Spreadsheet data to HTML

415

Property key f1taglib.source.<name>.chart.<name>.xslt.<name>=<value> f1taglib.source.<name>.chart.<name>=<value> f1taglib.source.<name>.entry.<name>=<value> f1taglib.source.<name>.formula.<name>=<value> f1taglib.source.<name>.merge.<name>=<value> f1taglib.source.<name>.range.<name>=<value> f1taglib.source.<name>.source.<name>=<value> f1taglib.source.<name>.spreadsheetformat.<name>=<value> f1taglib.source.<name>.table.<name>=<value> f1taglib.source.<name>.text.<name>=<value> f1taglib.source.<name>.value.<name>=<value> f1taglib.source.<name>.xslt.<name>=<value> f1taglib.source.<name>=<value>

Tag(s) that use the key InsertChart, InsertChartImageMap GetChart, InsertChart SetCell, SetRange GetCell, GetRange InsertRange GetRange, InsertRange, SetRange LoadBook InsertCell, InsertRange InsertRange GetCell, GetRange GetCell, GetRange InsertRange GetBook, GetCell, GetChart, GetRange, InsertCell, InsertChart, InsertRange, LoadBook, SetCell, SetRange, UnloadBook

e.Spreadsheet properties file for Data Pipes


There are no property keys for changing the defaults of, overriding, or redefining attributes of the data pipes tags (CreateDataQuery, CreateDataRange, CreateFileDataSource, CreateJDBCDataSource, RefreshData, and SetDataQueryParameter). Equivalent functionality is provided in a special e.Spreadsheet properties file that is linked to the VTS or XLS file. The entries you make in that file are similar to but not the same as the entries in the JSP Charting API properties file. Since Excel does not provide data pipes functionality, one of the most powerful uses of the e.Spreadsheet properties file is to create DataSources, DataQueries, and DataRanges for Excel files without having to convert the XLS file to VTS format first. You can use the data pipes defaults and overrides

416

Programming e.Spreadsheet Reports

established in a e.Spreadsheet properties file when the files VTS or XLS file is loaded into a JSP page with JSP Charting API tags. The JSP Charting API automatically reads in e.Spreadsheet properties files that follow these two guidelines:
s

The name of the e.Spreadsheet properties file must be the same as the VTS or XLS file, replacing the extension .vts or .xls with .properties. The e.Spreadsheet properties file must be stored in the same directory as the VTS or XLS file.

As long as the e.Spreadsheet properties file is named properly and stored in the proper directory, the JSP Charting API will automatically access that file and use the defaults and overrides contained in it when processing tags that use the VTS or XLS file linked that the properties file is linked to. For more information about the properties you can set in the e.Spreadsheet properties file and a code example, see Setting connection information with a properties file in Chapter 12, Connecting to external data.Setting connection information with a properties file.

Context parameters
Context parameters specify configurations for a particular installation configuration of the JSP Charting API. Context parameters appear in the web.xml file. They are XML elements that follow the following structure:
<context-param> <param-name>name of parameter</param-name> <param-value>value of parameter</param-value> </context-param>

Context parameters can appear in any order in the web.xml file, as long as they appear between the opening and closing <web-app> tags. If you do not specify values for these context parameters, the default values will be used.

Chapter 17, Converting e.Spreadsheet data to HTML

417

List of context parameters and their values


The following table lists all of the context parameters alphabetically by parameter name, describes what the context parameter does, and shows the possible values of each parameter, if applicable. Parameter name f1taglib.debug What the parameter does Allows you to hide the URL that results from insertion of a InsertDebug tag. This lets you leave your debugging tags in the JSP documents even after your web application goes live. The three possible values are: s hide, which saves the debug URL as a comment in the generated HTML, but shows nothing in the browser s ignore, which completely removes the debug URL from the generated HTML s show, which displays the debug URL in the generated HTML so that it appears in the browser. This is the default. Allows you to set the amount of disk space for the image cache, in kilobytes. The possible values are: s -1, indicating unlimited disk space for image cache. This is the default. s 0, indicating zero disk space for image cache s any non-negative number, indicating the number of kilobytes of disk space reserved for the image cache. Allows you to set the maximum number of background threads for image production. The default is 8.

f1taglib.image.disksize

f1taglib.image.maxthreads

418

Programming e.Spreadsheet Reports

Parameter name f1taglib.image.memorysize

What the parameter does Allows you to set the amount of memory for the image cache, in kilobytes. The possible values are: s -1, indicating unlimited memory for image cache. This is the default. s 0, indicating no image cache is maintained s any non-negative number, indicating the number of kilobytes of memory reserved for the image cache. Allows you to set the minimum number of background threads for image production. The default is 2. Allows you to set the name of the properties file. Allows you to set the name of the servlet directory. The default is servlet. Allows you to create a default directory where your data is stored.

f1taglib.image.minthreads

f1taglib.mapfile f1taglib.servletdirectory f1taglib.sourcedirectory

XML schemas for ranges and chart maps


The InsertRange, InsertChart, and InsertChartImageMap tags create output for JSP pages. To produce that output, the tags create XML that is then transformed by a built-in XSLT document. The XSLT document converts the XML output into the HTML tags that appear in the JSP page. Customers who want to alter how the XML output is transformed may choose to create their own XSLT documents to override the built-in ones that are shipped with the JSP Charting API. In order to produce good XSLT, customers need to know how the XML documents produced by these tags are structured: the elements and attributes, the valid attribute values, etc. This chapter details the XML schema for the XML output created by the InsertRange, InsertChart, and InsertChartImageMap tags.

Chapter 17, Converting e.Spreadsheet data to HTML

419

XML schema for ranges


The InsertRange tag converts ranges in e.Spreadsheet worksheets into HTML tables. The conversion process involves creating XML output that contains the actual data and converting that XML output into HTML <table>, <tr>, and <td> tags via a built-in XSLT document.

XML schema for chart image maps


The InsertChart and InsertChartImageMap tags create clickable image maps that allow web designers to assign URLs to different clickable areas on the chart. To create these image maps, the InsertChart and InsertChartImageMap tags create XML output that contains the coordinates of the edges of the bounding boxes that enclose each individual chart area. That XML output is then converted into HTML <area> tags via a built-in XSLT document. The following table lists the elements of the XML that is output by the InsertChart and InsertChartImageMap tags, along with their attributes and a description. Element <chartmap> Attribute name url <chart> <plot> <series> <datapoint> index name index name value <coords> <point/> x number (the x coordinates of the enclosing polygon the clickable area for each data point) number (the y coordinates of the enclosing polygon the clickable area for each data point) number (series index number) string (series name) number (data point index number) string (data point name) number (data point value) Description string (name of chart image map passed to setImageMapName method) string (URL passed to setDefaultURL method)

</coords> </data point>

420

Programming e.Spreadsheet Reports

Element <coords> <point/>

Attribute x y

Description number (the x coordinates of the series polygon) number (the y coordinates of the series polygon)

</coords> </series> <coords> <point/> x y </coords> </plot> <legend> <legenditem> index name <coords> <point/> x y </coords> </legenditem> </legend> <coords> <point/> x y </coords> </chart> </chartmap> array (the x coordinates of the legend polygon) array (the y coordinates of the legend polygon) array (the x coordinates of the legend item) array (the y coordinates of the legend item) number (index number of each legend item) string (name of each legend item) array (the x coordinates of the plot polygon) array (the y coordinates of the plot polygon)

Chapter 17, Converting e.Spreadsheet data to HTML

421

Viewing the JSP Charting APIs built-In XSLT documents


Customers who want to write their own XSLT documents to override the built-in XSLT that is shipped with the JSP Charting API may find it useful to view the built-in XSLT documents themselves. The built-in XSLT document that transforms worksheet ranges into HTML tables is called html.xsl. The built-in XSLT document that transforms chart image areas into HTML <area> tags is called imagemap.xsl. Both of these documents can be accessed in the example documents installed with the JSP Charting API test web app.

422

Programming e.Spreadsheet Reports

Chapter

18
Chapter 18

Troubleshooting

This chapter contains the following topics:


s s

Troubleshooting worksheet functions that return #DIV/0! Troubleshooting very slow screen redraws

Chapter 18, Troubleshooting

423

Troubleshooting worksheet functions that return #DIV/0!


Occasionally, a statistical worksheet function may return a #DIV/0 error when there is apparently valid data in a range of cells. Usually, this occurs when the range is pointing to a blank or empty area. Verify that the range is correct and make sure that the data has been added to the sheet as numbers, not as text.

Troubleshooting very slow screen redraws


When running the AWT version of the e.Spreadsheet Designer on the Java 2 version 1.2 platform, screen redraws may become extremely slow while repainting text on worksheets with a lot of text. This is the result of a bug specific to Java 2 version 1.2. This behavior does not occur in previous versions of Java, and appears to be fixed in Java 2 version 1.3.

Determining the behavior of circular recalculations


Iteration (repeated calculation) can be used to solve circular references. To use iteration: 1 Pass true to the setIterationEnabled method to turn on iteration. 2 Set the maximum number of iterations using the setIterationMax method. 3 Set the maximum amount of change with the setIterationMaxChange method. The e.Spreadsheet engine recalculates until it iterates the number of times specified by the setIterationMax method or until all cells change by less than the amount specified in the setIterationMaxChange method.

Using the e.Spreadsheet Designer


1 Choose ToolsOptions. 2 Select the Calculation tab. 3 Set the maximum number of iterations and maximum amount of change. 4 Select Iteration to activate your settings; deselect to deactivate.

424

Programming e.Spreadsheet Reports

Code Example
jbook1.setIterationEnabled(true); jbook1.setIterationMax(500); jbook1.setIterationMaxChange(.001);

Comparing IF condition statement values correctly when a text value is entered


When using the IF function, a numeric value must be compared to another numeric value or a text value must be compared to another text value. When the cell has the following formula:
=if(A1=1,"true","false")

and cell A1 contains a text value (or any number other than 1), the IF statement will return false.

Chapter 18, Troubleshooting

425

Using e.Spreadsheet in the main class causes problems


Using e.Spreadsheet in the main method of an application may cause the application to hang. This results from a JDK bug for which the only workaround is to call System.exit(0). It exhibits the same behavior (the program hangs after the main method finishes) in both the Swing and AWT versions. Programs that use e.Spreadsheet in the main method hang because when java.awt.SystemColor is loaded, it calls Toolkit.getDefaultToolkit, which creates two AWT threads. These threads never stop, and they are not daemon threads, so the program hangs. This bug has been reported to Sun. (#4030718)A program that calls Toolkit.getDefaultToolkit wont terminate. Unfortunately, just getting a system color causes this problem. Try the following example:
public class SimplCon { static public void main(String args[]) { java.awt.Color color = java.awt.SystemColor.window; } }

426

Programming e.Spreadsheet Reports

Chapter

19
Chapter 19

Using e.Spreadsheet with Unix

This chapter contains the following topics:


s s s s

Introduction Using e.Spreadsheet on Unix with a graphics device Using e.Spreadsheet on Unix without X-Windows Using setColWidthAuto with no GUI

Chapter 19, Using e.Spreadsheet with Unix

427

Introduction
In most cases, e.Spreadsheet runs within the Unix or within a Unix-like operating system (Linux, Solaris, SunOS, etc.) exactly the same as it runs within other operating systems. However, due to limitations in Swing, JBook requires access to the X windowing environment which is set through the DISPLAY environment variable. In this chapter, two solutions for this limitation are presented along with a note about using the setColWidthAuto method with the setColWidthAuto method with the BookModelImpl class and in GUI-less environments.

Using e.Spreadsheet on Unix with a graphics device


Trying to instantiate e.Spreadsheets JBook on a machine running a Unix OS results in the error:
"java.lang.InternalError: Cant connect to X11 window server using :0.0 as the value of the DISPLAY variable."

On any platform, instantiating e.Spreadsheets JBook requires access to a graphics device. On Unix, the graphics hardware is accessed through the X11 windows environment. If the application does not render charts as images or call the setColWidthAuto method, use the BookModelImpl class which has almost all the functionality of a JBook, without the overhead of the AWT event thread. For more information and a code example, see Creating servlets and applications with no GUI overhead in Chapter 14, Deploying on a server.Creating servlets and applications with no GUI overhead. When converting code developed using the JBook class to a GUI-less servlet or application, the setColWidthAuto method will no longer function as expected. For more information, see Using setColWidthAuto with no GUI later in this chapter.Using setColWidthAuto with no GUI. To set up the DISPLAY variable on a Unix/Solaris machine: 1 If the Web Server has a graphical device on it, make sure X is running. 2 The error message described above generally means that the hostname is not set for the machine. Make the DISPLAY variable read something like
- DISPLAY=MYSolBox:0.0; export DISPLAY

Where: MYSolBox is the hostname or IP address of the web server.

428

Programming e.Spreadsheet Reports

3 Open a terminal window on MYSolBox and type:


xhost +

This allows the external application to access the X server. Or 1 If the web server does not have a graphical device, set the DISPLAY variable to an X11 server somewhere on the network. For example:
DISPLAY=JoesMachine:0.0; export DISPLAY

2 Then go to "Joes machine," open a terminal window, and type:


xhost +

Some web servers do not pass the environment variables to the JVM when running servlets. The Apache/JServ combination is an example of such a web server. To set the display variable in these cases, add the following line to the jserv.properties file.
wrapper.env=DISPLAY=MySolBox:0.0; export DISPLAY

Using e.Spreadsheet on Unix without X-Windows


As discussed in the previous article, e.Spreadsheet can normally be used on a server without an X-Windows environment running by using the GUI-less, server-optimized BookModelImpl class instead of the JBook class. A problem arises in cases where the JBook class must be used or other graphics (including charts) are generated. Sun explains in an FAQ description (java.sun.com/products/java-media/2D/forDevelopers/java2dfaq.html) that calling getGraphics in a UNIX OS always initializes the X server display which will throw an exception unless an X server is running. Sun plans to fix this limitation in the future. Until Sun fixes this, in order to generate charts or access any other feature that requires the use of e.Spreadsheets JBook class in Unix, the following options are available.

Chapter 19, Using e.Spreadsheet with Unix

429

Options for running without X-Windows


1 Point the servers DISPLAY variable to another machines X-Windows environment. See Using e.Spreadsheet on Unix with a graphics device earlier in this chapter.Using e.Spreadsheet on Unix with a graphics device. 2 Install a virtual X server on your Unix box: a. Xvfb classes provide native binary executables which accept X11 calls and allow the JBook to be fully functional. b. Eleks PJA (pure Java AWT) Toolkit provide a set of Java classes that emulate an X server within the web server

To instantiate an Xvfb virtual server in a Unix environment:


1 Download Xvfb from www.x.org or another source. 2 Enter the following commands from a command prompt (works in a Linux Redhat 7.0 environment) to run the X server:
/usr/X11R6/bin/Xvfb :1 -screen 0 800x600x24 -fp /usr/X11R6/lib/X11/fonts/misc & DISPLAY=:1.0 export DISPLAY

The commands may vary based on the web server environment. Consult the Xvfb and server documentation for information and instructions specific to your server environment.

To emulate an X Server within the web server using PJA Toolkit:


1 Download the classes from www.eteks.com/PJA. (The PJA website is in French. To view it in English, click the British flag in the upper-right corner.) 2 Edit the startup scripts to replace the PJA classes in the System graphics toolkit To install PJA Toolkit on Tomcat, add the following after the set TOMCAT_HOME=install_directory\tomcat32 line:
set TOMCAT_OPTS = -Xbootclasspath/a:%TOMCAT_HOME%/lib/pja.jar -Dawt.toolkit = com.eteks.awt.PJAToolkit -Djava.awt.graphicsenv = com.eteks.java2d.PJAGraphicsEnvironment -Djava2d.font.usePlatformFont = false -Djava.awt.fonts = %TOMCAT_HOME%/lib/ttfonts -Duser.home = %TOMCAT_HOME%

3 Copy the PJA jar files into TOMCAT_HOME/lib.

430

Programming e.Spreadsheet Reports

4 Restart the server. The best quality output will probably result from the X11 server software running with a graphics card. Xvfb has a speed advantage over PJA because it is natively-compiled code, but requires specific startup scripts to instantiate it. PJA provides the most portable solution for Java web applications, but requires a Java-based server to execute. It is also a bit more complicated to set up.

Using setColWidthAuto with no GUI


The setColWidthAuto method does not work with BookModelImpl class instantiations of e.Spreadsheet. The setColWidthAuto method uses the font metrics available in a GUI interface to automatically set the column width, and returns an exception when it does not find them. For more information and an example of a GUI-less servlet, see Creating servlets and applications with no GUI overhead in Chapter 14, Deploying on a server.Creating servlets and applications with no GUI overhead. For more information about using the setColWidthAuto method, see Resizing columns as data changesResizing columns as data changes and Changing default column width in Chapter 8, Formatting worksheets.Changing default column width.

Chapter 19, Using e.Spreadsheet with Unix

431

432

Programming e.Spreadsheet Reports

Appendix

A
Chapter 19

Additional Information

This appendix contains the following information:


s s s s

e.Spreadsheet maximums and minimums Links to more information Converting legacy code from AWT to Swing e.Spreadsheet files
Appendix A

Chapter 19, Additional Information

433

e.Spreadsheet maximums and minimums


Parameter Maximum worksheet size Maximum number of worksheets in a workbook Column width Row height Cell Text length Formula length Number precision Largest positive number Largest negative number Smallest positive number Smallest negative number Maximum number of iterations Maximum number of colors Maximum number of available colors Maximum number of fonts per sheet Maximum number of selected ranges Maximum number of names per sheet Maximum length of name Maximum number of function arguments Maximum length of format string Maximum number of tables Excel file format version Number of worksheet functions Maximum number of points in a polygon Limits of date range Specification 1,073,741,824 rows by 32,768 columns 32,768 0 to 255 characters 0 to 409 points 32,767 characters 1,024 characters 15 digits 9.99999999999999E307 -9.99999999999999E307 1E-307 -1E-307 32,767 56 Limited by display card and monitor 256 2,048 16,384 255 30 255 Limited by system resources Excel 5.0 and 7.0, 97, 2000, and 2002 (Office XP) 325 8,191 1/1/1900 to 12/31/9999

434

Programming e.Spreadsheet Reports

Links to more information


URL www.actuate.com www.java.sun.com www.rsasecurity.com www.belsign.com www.verisign.com www.thawte.com developer.netscape.com www.foldoc.org docs.sun.com java.sun.com/docs/ glossary.html Description Actuates e.Spreadsheet Division Web Site Sun Microsystems Java Information Web Site RSA Data Security Web Site BelSign (Certificate Authority) Web Site VeriSign (Certificate Authority) Web Site Thawte Consulting (Certificate Authority) Web Site Netscape DevEdge Online Free On-Line Dictionary of Computing Glossary of Sun Terms Glossary of Java Terms

Converting legacy code from AWT to Swing


The main difference between the AWT and Swing API is related to the name of the View class. In AWT it was named View. In Swing, to access the Swing View, the class is named JBook. The following table summarizes other minor changes which must be made to existing AWT View source code to access the Swing JBook members. The AWT component is deprecated. This includes the com.f1j.View package and associated classes. AWT API import com.f1j.* Swing API import com.f1j.util.*; import com.f1j.swing.*; import com.f1j.ss.*; f1j.ss.CellFormat f1j.ss.setValueFormat

f1j.CellFormat f1j.CellFormat.setNumberFormat

Appendix A,

435

AWT API (continued) f1j.CellRef f1j.Database f1j.F1Exception f1j.FindReplaceInfo f1j.GRObject f1j.GRObjectPos f1j.JDBC f1j.JDBCQueryObj f1j.RangeRef f1j.View f1j.View.setLaunchWorkbookDesigner f1j.View.setParentFrame

Swing API (continued) f1j.ss.CellRef f1j.calc.Database (constructor null) f1j.util.F1Exception f1j.ss.FindReplaceInfo f1j.ss.GRObject f1j.ss.GRObjectPos f1j.jdbc.JDBC f1j.jdbc.JDBCQueryObj f1j.ss.RangeRef f1j.swing.Jbook f1j.swing.Jbook.setAllowDesigner Does not exist. Instead use:
Frame f = new Frame(); f.add(Jbook1);

e.Spreadsheet files
The following files comprise the e.Spreadsheet software product. For information on which of these files are required to deploy applications and applets using e.Spreadsheet, see Required files for e.Spreadsheet deployment in Chapter 1, Programming with e.Spreadsheet.Required files for e.Spreadsheet deployment. e.Spreadsheet files Program files These files contain the e.Spreadsheet program. f1j9swing.jar The Swing version of the e.Spreadsheet JavaBean, applet, and application. (The name f1j9swing.jar indicates which Java GUI classes the JAR file can be used with. f1j9swing.jar does not include Javas Swing classes, just e.Spreadsheets Swing-specific classes.) The AWT version of the e.Spreadsheet JavaBean and applet (but not the application).

f1j9awt.jar

436

Programming e.Spreadsheet Reports

e.Spreadsheet files (continued) f1j9awtdesign.jar F1J9.exe f1j9.ini The AWT version of the e.Spreadsheet JavaBean, applet, and application. (installed on Windows only) A Windows executable that launches the e.Spreadsheet application. (installed on Windows only) An INI file that lets you configure f1j9.exe in order to specify a particular JVM, set of Swing classes, e.Spreadsheet JAR file, etc.

Supporting JAR files These JAR files contain classes used by e.Spreadsheet when performing particular functions. Because they are not part of the core Java platform or otherwise accessible from most computers, developers who want to access their functionality must ship them along with their product. infobus.jar The Java classes for the InfoBus Java extension. Some of these classes may be called from the e.Spreadsheet API. Java classes that enable e.Spreadsheet to process XSLT documents. Java classes that enable e.Spreadsheet to read in XML files. The file crimson.jar replaces xerces.jar, which was used in e.Spreadsheet 8.0. A Java interface that allows e.Spreadsheet to communicate with JAXP-compliant XML parsers and XSLT translators like crimson and xalan.

xalan.jar crimson.jar

jaxp.jar

Utilities This file helps with the uninstallation of e.Spreadsheet. Uninst.isu A Windows-specific log file the Windows uninstaller uses to remove the software from the computer.

Appendix A,

437

Documentation These files and directories contain basic documentation for getting started with e.Spreadsheet. For more information on documentation, see About Actuate e.Spreadsheet Designer product in the introductory chapter.About Actuate e.Spreadsheet Designer product. readme.html Basic information on installation and known bugs and limitations of the product. All of the other HTML files in this section are linked to from the ReadMe. A list of the Excel 3D chart types and the type of chart they will be converted to in e.Spreadsheet. A list of features that have some degree of incompatibility with Excel. Documentation on how to add the e.Spreadsheet JavaBean to various Java development environments. A list of the new and enhanced features of e.Spreadsheets 9.0 version. A list of issues involving worksheet function compatibility with Excel.

chart_types.html

excel_compatibility.html f1j_ide.html

features.html function_readme.html

Javadoc These files and directories contain documentation of the e.Spreadsheet API generated by the Java tool Javadoc. help/awtdoc Directory containing documentation for e.Spreadsheets AWT component, in HTML format. Directory containing documentation for e.Spreadsheets Swing component, in HTML format. (Windows only) A searchable online help file containing documentation for e.Spreadsheets Swing component. This is the same information as in the swingdoc directory, only in a different format.

help/swingdoc

help/win/f19api.chm

438

Programming e.Spreadsheet Reports

Examples These directories contain a tutorial, examples, and demos. For specific information about demos, see Javadoc-generated guide to all of e.Spreadsheets public API. The API Help is available as Javadoc in the install_dir/help/awtdoc and install_dir/help/swingdoc directories and as an HTML Help file in the install_dir/help/win directory. in Chapter 1, Programming with e.Spreadsheet.Javadoc-generated guide to all of e.Spreadsheets public API. The API Help is available as Javadoc in the install_dir/help/awtdoc and install_dir/help/swingdoc directories and as an HTML Help file in the install_dir/help/win directory.. examples/ servlets/ Several sets of example code showing how to use e.Spreadsheet code in applications and applets. Servlet example code (both the Java and resulting class files) and a readme.

JavaHelp files These are online help files. For more information on documentation, see About Actuate e.Spreadsheet Designer productin the introductory chapter.About Actuate e.Spreadsheet Designer product. f1help.jar e.Spreadsheet user documentation help set in the JavaHelp format. Includes the contents of Designing e.Spreadsheet Reports and e.Spreadsheet Java Edition Function Reference in HTML and XML. The Java classes that run the JavaHelp system. You must use this JAR file if you want to view the online help through the e.Spreadsheet Designer. The help content files are stored in f1help.jar.

jh.jar

Appendix A,

439

Windows Help files These are searchable online help files for Windows users. These files are installed only on Windows machines. For more information on e.Spreadsheets Windows documentation, see About Actuate e.Spreadsheet Designer product in the introductory chapter.About Actuate e.Spreadsheet Designer product. help/win/es-programming.chm help/win/es-functions.chm help/win/es-help.chm Programming e.Spreadsheet Reports (this manual) e.Spreadsheet Function Reference A master helpset that lets you access all of e.Spreadsheets Windows documentation at once. Designing e.Spreadsheet Reports Programming e.Spreadsheet Web Applications

help/win/es-designing.chm help/win/es-webapps.chm

PDF files These files contain online versions of the e.Spreadsheet documentation in a format that is easy to print. For more information on PDF files, see About Actuate e.Spreadsheet Designer product in the introductory chapter.About Actuate e.Spreadsheet Designer product. help/pdf/es-programming.pdf help/pdf/es-functions.pdf help/pdf/es-designing.pdf help/pdf/es-webapps.pdf Programming e.Spreadsheet Reports e.Spreadsheet Function Reference Designing e.Spreadsheet Reports Programming e.Spreadsheet Web Applications

440

Programming e.Spreadsheet Reports

Tutorial These files are tutorials designed to help developers use the e.Spreadsheet API. For more information on documentation, see About Actuate e.Spreadsheet Designer product in the introductory chapter.About Actuate e.Spreadsheet Designer product. help/tutorial/ tu_1_swing.pdf help/tutorial/ tu_2_swing.pdf A tutorial that illustrates the basics of using the e.Spreadsheet API. The PDF file contains the tutorial text and Java code. A tutorial that explains how to use e.Spreadsheets charting classes. The PDF file contains the tutorial text and Java code.

Full Translation and language-enabled files For a list of jar files used to deploy e.Spreadsheet in full translations and language-enabled modes, see the separate publication, e.Reporting for Multiple Locales.

Extras This installation pack contains extra files that are necessary for some of e.Spreadsheets functions. f1jtextures.jar A JAR file containing image files for e.Spreadsheets textured fills.

Appendix A,

441

442

Programming e.Spreadsheet Reports

Index
Symbols
$ (currency) 153 $ (string) 70, 342, 349 158 % (percent sign) 378 & (ampersand) 95, 347 * (asterisk), in properties file 412 /n (new line) 349 < (less-than) 263 < (open angle bracket) 373 < (supplied argument, delimiter) xxviii > (close angle bracket) 373 > (greater-than) 263 @ (at sign) 378 [ (optional, array) xxviii [ ] (array) 90, 91, 142, 146, 172, 180, 241, 318, 319 [0] notation in variable names 377 { (grouped arguments, array, delimiter) xxviii | (argument separator, OR operator) xxviii (forward slash) 373 Advanced e.Reporting Server Progress Edition xix analysis tools (third-party) xvii e.Analysis application xix e.Report Designer xviii e.Report Designer Professional xvii e.Reporting Suite 5 xvi, xvii End User Desktop xx LRX (Live Report Extension) xx online reports xvi Release notes xxii report server API xvii reporting solutions xvi Requester API xvii sample e.Analysis application xix search extension API xvii Software Development Kit xvii third-party analysis tools xvii Viewer xx web site xxii Add-in functions 1822 demos xxii, 24 Adding custom formats to the Format Cells Dialog 156 empty rows and columns 52 graphics objects to a worksheet 172181 graphics objects with addObject 173 text areas 179 white space to a worksheet 52 worksheets to a workbook 108 worksheets to web pages 270 Advanced e.Reporting Server xix Advanced e.Reporting Server Progress Edition xix Aligning data in cells 140 Allaires JRun, see JRun Amortization example 297 servlet example 288 Amortization demo 24 Ampersand symbol (&) 95, 347 Apache/JServ web server 429

A
Absolute reference 70, 342, 349 value 117 action attribute of CreateDataQuery tag 383 of CreateDataRange tag 384 of CreateFileDataSource tag 386 of CreateJDBCDataSource tag 388 Active cell making visible 78 moves down 78 sheet deleting 108 getting name of 111 getting when changed 48 Actuate

Index

443

API accessing 37 accessing using JavaScript 302 Actuate report server xvii Actuate Requester xvii Actuate search extension xvii documentation for e.Spreadsheet 23, 438 primary classes and interfaces 10 using constants in code 17 Applets 2737 and Netscape Navigator 31 and RSA verification 30 APPLET tags 8, 35, 270, 271, 302, 315 converting signed 31 creating 267 creating RSA signed 30 demos, finding xxii deploying signed 35 example 4 loading worksheet with embedded 315 mistakes/solutions when deploying 35 preparing for Internet Explorer 33 reading, writing, printing files from 36 setting permission levels for 34 Application deploy directory, for JRun installation 360 Application host, for JRun installation 360 Application name, for JRun installation 360 Application URL, for JRun installation 360 Applications and Java security 30 changing garbage collection in 54 demos xxii e.Spreadsheet in main method of 9 embedding e.Spreadsheet in 270 example 4, 37 using memory efficiently in 52 using the BookModel object with 294 using VTS files in 271 ARCHIVE path 302 Arcs adding with addObject 173 drawing with setMode 175 <area> tag, in HTML 377 Array variables, single-element 376 Arrays allocating references and performance 54

and data structure 55 array entered formulas 70 byte arrays used with blob 318 conditional format 149 converting/saving images as byte 172 copying data from 91 creating and loading data from 90 integer arrays to set breaks 241 points on a polygon 181 using to format cells (example) 142 aspect attribute chart sizing and 394 of GetChart tag 392 of InsertChart tag 400 Attach method, example 116, 119 Attributes 374 book attribute 375 default values for, setting 411 overriding values of, in properties file 412 redefining values of, in properties file 413 syntax of 374 values of 374 Automatic column width adjustment 117, 170 recalculation 57 recalculation of add-in functions 22 sheet scrolling 131 text orientation 163 Automating reporting tasks xvii AWT event thread 428

B
Background threads and grouping workbooks 119 and system performance 5459 Backgrounds and text color 162 cell color 134 cell color to show a pattern 135 for graphics objects 181 graphics objects colors 187 in HTML using BGCOLOR tag 273 Bad magic number error 35 Beas WebLogic 359 BelSign 30 Binary large object, See Blob

444

Programming e.Spreadsheet Reports

Black-Scholes demo 24 Blank cells, formatting 52 Blob determining length 319 reading and writing 318 Bodies, in tags 374 Bold font formatting 117, 161 font formatting in header 348 book attribute 375 book attribute of CreateDataQuery tag 382 of CreateDataRange tag 384 of CreateFileDataSource tag 386 of CreateJDBCDataSource tag 387 of GetBook tag 390 of GetCell tag 390 of GetChart tag 391 of GetRange tag 397 of InsertCell tag 399 of InsertChart tag 399 of InsertRange tag 403 of LoadBook tag 405 of RefreshData tag 406 of SetCell tag 407 of SetDataQueryParameter tag 407 of SetRange tag 408 of UnloadBook tag 409 Book object and garbage collection 54 examples using 20, 96 using with writeURL 274 write 318, 320 BookModel object, using 294 Borders formatting 112 removing worksheet border 112 using draw to print without 201 Browsers, e.Spreadsheet compatible 271 Bugs JDK bugs application hangs 426 buttons 190 graphics and Unix OS 429 objectClicked/objectDblClicked 190 printing and garbage collection 354 printing in landscape with draw 341

slow screen repaint 424 suppressing print dialog 340 listed in readme 438 Buttons adding with addObject 173 bug 190 dialog box 43 drawing with setMode 175 example button code 188 byBookData[] variable of GetBook tag 390 Byte array, See Arrays

C
CA, See Certificate Authority CAB files signing 33 using CABBASE when embedding applets 270 cabarc.exe 33 Calculation demo 24 Callback classes executing 227 report server and 228 Canceling user entry 49 Cannot find a .class file 36 Cannot find javasign.dll 36 Capabilities API Classes 36 Carriage returns, inserting 347 cell attribute of GetCell tag 391 of InsertCell tag 399 of SetCell tag 407 Cell Manipulation 6380, 87, 101 cellkeys attribute of InsertRange tag 404 Cells aligning data in 140 and memory size 56 assigning an index value 186 background color 134 background patterns 135 contents, getting from relative cell location 166 coordinates 77 displaying multi-line data in 138 formatting 133 formatting blank 52

Index

445

getting cell location and size in pixels 184 location as string 98 reference 66 hiding values 143 hyperlinking from 143 inserting 64 locking and unlocking 82, 139 making active cell visible 78 making background a solid color 134 maximum number of characters 59, 434 merging 137 naming 101 protecting 8182, 139 setting text color in 162 showing active cell 78 type constants 97 cert7.db 31 Certificate Authority 2930, 33 Certificates, contents 29 Changing See also converting, creating, deleting, and setting class path ??42 default font 117, 162 defined name 101 font 160 items in a dropdown list box 193 look and feel 109 number of sheets in a workbook 108 number of visible rows and columns 85 page setup attributes 345 sheet name 122 sheet type 109 viewable data using outlining 113 worksheet names 122 Character-delimited text, See Delimited text characterdelimiter attribute of CreateDataQuery tag 383 of CreateFileDataSource tag 386 Characters limiting number in a cell 84 maximum number in a cell 59, 434 chart attribute of GetChart tag 392 of InsertChart tag 399 chart_types.html file 438

chartmap attribute of InsertChart tag 401 of InsertChartImageMap tag 402 Charts adding to worksheet from code 176 adding with addObject 173 drawing with setMode 175 formatting 176 GetChart tag for 391 InsertChart tag for 399 InsertChartImageMap tag for 401 variables for imagemaps 377 writing images as GIF or PNG 330 Checkboxes adding with addObject 173 centering in a column 188 drawing with setMode 175 chkjava.exe 35 Circular recalculations, solving 424 Class files in JRun shared installation 363 single installation 362 in TomCat shared installation 370 single installation 368 Class path changing ??42 changing settings in JVM 40 Classes Book 20, 54, 96, 275, 310, 318, 320 BookImpl 13, 15, 310 BookModel 292, 294, 310 BookModelImpl 13, 293, 310, 428 Callback 226 CellFormat 13, 15, 134, 165 CellRef 15 ChartImageEncoder 10, 13, 14, 330 ConditionalFormat 146 Database 12 DatabaseQuery 208 DataQuery 208 DataQueryCollection 208 DataRange 246 DataRangeImpl 12, 209 DataSourceCollectionImpl 231 DelimitedText 211

446

Programming e.Spreadsheet Reports

Designer 13, 14 DOM 209 events, see Events executing from the Designer 226 F1Exception 13 FindReplaceInfo 15 FormatCellsDlg 13 Func 12, 18 GRChart 173 GRObject 15, 173, 176, 191 GRObjectPos 15 Group 14 Handler 210 HTMLWriter 13, 14, 290, 297 ImageEncoder 330 InfoBusBook 12 JBook 13, 14, 96, 293, 435 JBookApplet 13, 302 JDBC 209, 212, 229 JDBCDlg 208 JDBCImpl 208 JDBCQueryObj 209 JDBCQueryObjImpl 208 listeners, see Events Main 426 making private 19 NumberFormat 15 PageSetupDlg 13 PositionalText 211 primary 14 PrivilegeManager 36 Query 209 RangeRef 15 ReadParams 308, 310 returned from JBook 15 Sheet 73, 109 SheetImpl 13 Text 211 unjarring from JAR files 33 utility classes 14 View 435 WriteParams 308, 310 XMLWriter 14, 324 Clearing See also Deleting cell contents 71 cells 73

cells before in-cell edit 87 Clearing, Cutting, and Deleting 71 data only 72 existing database formatting 257 from cells with protection enabled 73 left over settings 39 outlines 113 print area 342 print titles 349, 350 the edit bar 87 using clearRange 70 editClear 71, 72, 80 editCut 73 values only 80 Code examples xxii pages, setting 310 setting file type to read in or write 310 Colors maximum number of 434 printing 343 setting for an object 187 cell background 134 cell type 139 conditional formatting 146 font 161 HTML 273 numbers 152 text 162 type markers 139 columnnames attribute of CreateDataQuery tag 383 of CreateFileDataSource tag 386 columnpositions attribute of CreateDataQuery tag 383 of CreateFileDataSource tag 386 Columns adding for white space 52 automatically resizing width. 129 coordinates 69 determining last to contain data 67 fixing and unfixing 128 getting reference 66 getting/setting header size and text 123 header font, setting 124

Index

447

headers, reverting to default 126 headings, printing 346 hiding 85, 127 including names in connected data 243 inserting 64 maximum number in worksheet 434 maximum width 434 multi-line data in headers 126 printing titles 350 protecting 81 resizing window when size changes 117 restricting editing in 80 selecting entire for print titles 349 selecting headers 66 setting first displayed 131 left-most displayed 131 width before loading in data 127 shifting after delete 73 showing headings 125 width adjusting automatically 117, 129, 170 getting 130 Comma-delimited converting range of data to text 322 data source files 239 files, saving workbooks as 323 formulas, maximum length 59 list of active ranges 66 Comments, in properties file 410 Compatibility browsers 271 XML 255 Compression (image) technology 330 Concatenating text 95 Concatenation (example add-in) 18 Concatenation demo 24 Conditional formatting 146 tags used in XML 262 Configuring the JSP Charting API JRun shared installation 363 single installation 362 TomCat shared installation 371 single installation 368 Connecting

multiple workbooks (grouping) 119 Constants using API constants 17 cell formatting mode 257 cell insert modes 251 Constants interface 17 for borders 112 cell data orientation 164 data type 97 formatting modes for imported data 250 shift mode used with deleteRange 74 clearType 71 dataType 256 file type 321 hiddenState 111 horizontal and vertical alignment 140 mouse action modes 175 patterns 136 sourceType 230 text direction 163 what (to paste) 76 Context parameters 417 for properties file 410 list of 418 Converting code to eliminate GUI overhead 293 data to tab-delimited text 322 HTML code to work with the Java Plugin 270, 271 images to byte arrays 172 Netscape applets to RSA signed applets 31 numbers to text 167 pixels to twips 50 worksheet data to XML 324 x, y coordinates to pixels or twips 184 Coordinates, See X, y coordinates Copying ??7174 making shortcut key for 76 CreateDataQuery tag 382 examples of 379 CreateDataRange tag 383 examples of 379 CreateFileDataSource tag 386

448

Programming e.Spreadsheet Reports

examples of 379 CreateJDBCDataSource tag examples of 379 crimson.jar file 437 CTRL key 77 Currency setting number format to 152157 setting symbol 153 Custom number formats, adding 156 Cutting, See Clearing, Deleting

D
Data access using Data Pipes 205255 adding in variable rows in a column 69 aligning in cells 140 connecting to in an external file 237 converting to tab-delimited 322 converting to XML 255265 creating connection to external database 229 data pipes architecture (diagram) 207 entry using code 88 formatting using XSLT 248, 324 getting current cell data 47 including column names with 243 maintaining formatting from database 248 moving or deleting ranges 253 multi-line 126 displaying 138 range properties 248 ranges, setting up in data pipes 246 source connection using data pipes 237 source refresh options with data pipes 243 structure and memory size 55 type constants 97 data attribute of LoadBook tag 405 Data Pipes 206255 API changes in e.Spreadsheet 208 Deprecated API 208 file format change in e.Spreadsheet 208 new API in existing classes 209 new interfaces 209 setting properties 315 using e.Spreadsheet parameters 225 Data pipes

CreateDataQuery tag for 382 CreateDataRange tag for 383 CreateFileDataSource tag for 386 CreateJDBCDataSource tag for 387 properties file for 416 RefreshData tag for 406 SetDataQueryParameter tag for 407 database attribute of CreateJDBCDataSource tag 387 Databases connecting to via data pipes 229 DBMSs compatible with e.Spreadsheet 206 display properties with data pipes 248 handling imported dates 159 maintaining formatting using e.Spreadsheet 248 querying using data pipes 236 Databases, stored procedures from 382 datapoint attribute of InsertChart tag 401 of InsertChartImageMap tag 402 datapointurl attribute of InsertChart tag 401 of InsertChartImageMap tag 402 dataquery attribute of CreateDataQuery tag 382 of CreateDataRange tag 384 of SetDataQueryParameter tag 407 datarange attribute of CreateDataRange tag 384 of RefreshData tag 406 datasource attribute of CreateDataQuery tag 382 of CreateDataRange tag 384 of CreateFileDataSource tag 386 of CreateJDBCDataSource tag 387 of RefreshData tag 406 of SetDataQueryParameter tag 407 Date displaying in local format 158 entering from code 88 formatting to show four-digit year 158 four-digit year format in headers and footers 353 incrementing 89 Julian calendar 159

Index

449

preventing automatic formatting 48 range, limits of 434 sorting correctly with other data 94 Debugging, tag settings 418 Default cell protection status 73, 82 column width unit 131 Enter key moves down 78 font, changing 117 font, scaling proportionally 162 look and feel 109 sheet protection status 139 XML parser 263 Defaults directory for JSP pages 419 directory for servlets 419 for attribute values 411 overrides and, for attribute values 412 Defined names and garbage collection 54 changing 101 getting 98 getting number in use 103 named range 69 Delete key 80 Deleting See also Clearing active sheet 108 cells 73 Clearing, Cutting, and Deleting 71 data range connections in data pipes 253 items from a dropdown list box 195 objects during run time 187 values only 80 Delimited data 383, 386 Delimited text adding list items using addItem 193 as data source files 239 connecting to file via data pipes 237 constant 256 converting data to 322 identical with Unicode with UTF-16 312 list of active ranges returned as 67 preventing numbers as text in 323 saving a file as 323 using to enter listbox items 177 writing using setClip 91

Demos add-in function 24 amortization 24 Black-Scholes 24 concatenation 24 example application and applet 4 finding xxii, 23, 439 formatting API 24 page compilation 24 servlet 439 threading issues 24 Deploying BookModelImpl with no GUI 292 internationally, See e.Reporting for Multiple Locales required files 9 server-side 287 signed applets 35 Deselecting worksheets from code 111 Designing e.Spreadsheet Reports 439 Development environments 18 dGetCellValue[0] variable of GetCell tag 377, 391 dGetRangeValue2[][] variable of GetRange tag 398 dGetRangeValue3[][][] variable of GetRange tag 398 Dialog box 43 Dialogs ??43 Digital signatures 2837 Disk space for images, setting 418 required by JSP Charting API 357 Display scale, setting 116 Displaying active cell 78 borders 201 cell type color codes 139 cell value 143 charts in worksheets 173 connected data ranges 246 data converted to HTML 273 data from multiple workbooks 316 dates 88 dates in local format 158 edit bar 8, 116, 303 first row or column 131

450

Programming e.Spreadsheet Reports

foreground and background color 134 formula value or text 142 four-digit year date format 158 graphics objects in worksheets 173 gridlines 112, 201 header text 123 images in worksheets 172 large numbers 157 limited views 116 limited worksheet area 131 limiting visible rows and columns 85 list box items in a cell 194 messages using messageBox 43 more than 15 significant digits 169 multiple-line data 138 numbers as numbers 323 numbers in scientific notation 157 objects in worksheets 173 original column and row headers 126 print dialog 340 row and column headers 125 scroll bar 132 several files in one workbook on different tabs 316 text as text 323 in blue, etc, 152 vs. value 142 type markers 139 value formats etc 152 value vs. text 142 worksheet outlining 113 worksheet tabs 121, 122 > and < as text using XSLT 263 Document Object Model (DOM) API 209 Documentation about this xxi file locations 438 in the JavaHelp system 439 Javadoc output 23, 438 online xxiv organization xxi summary of e.Spreadsheet xxii syntax conventions xxvii DOM parser 263 Drag/drop, disabling 84

driver attribute of CreateJDBCDataSource tag 387 Dropdown list boxes 193196 adding and changing items in 193 adding with addObject 173 deleting items from 195 drawing with setMode 175 getting items out of 195

E
e.Analysis application xix e.Report Designer xviii e.Report Designer Java Edition xviii e.Report Designer Professional xvii e.Reporting Server Progress Edition xix e.Reporting Suite 5 xvi, xvii e.Spreadsheet Designer xviii about 2 documentation xxii online help 10 preventing from launching 4 selecting objects in 185 slow screen repaint in Java 2 424 textures in 10 translating dialogs and menus 10 Function Reference (publication) xxiii, 439 parameters 225 Server Option xx technical specifications 434 e.Spreadsheet files 375 Edit mode getting whether user is in 46 initiating 87 saving or deleting user entry 49 Eleks PJA 430 E-mail, accessing via a hyperlink 144 EMBED tags 8, 271 Embedding applets in web pages or applications 270 Encoding setting file type to read in or write 310 Enter key moves to next row 78 entry attribute of SetCell tag 407 of SetDataQueryParameter tag 408

Index

451

of SetRange tag 408 Error messages #DIV/0 424 suppressing 167 Errors bad magic number error 35 commonly made when signing applets 35 invalid argument error 68 ISERROR function 167 security error 35 troubleshooting missing files errors 39 wrong syntax 35 Events 4550 ActionListener 176 CancelEditEvent 15, 46 CancelEditListener 15 ChartEvent 15 ChartListener 15 ChartViewEvent 15 ChartViewListener 15 EndEditEvent 16, 46, 47, 48, 84, 85, 98 EndEditListener 16, 48 EndRecalcEvent 16 EndRecalcListener 16 HyperlinkEvent 16 HyperlinkListener 16 KeyEvent 47 KeyListener 76 list of 15 ModifiedEvent 16, 46 ModifiedListener 16 MouseEvent 50 ObjectEvent 16, 188, 190, 191, 192 ObjectListener 16, 188 SelectionChangedEvent 16, 48, 82, 83, 174 SelectionChangedListener 16 StartEditEvent 16, 46, 80, 83, 98 StartRecalcEvent 16 StartRecalcListener 16 UpdateEvent 16 UpdateListener 16 ValidationFailedEvent 16 ValidationFailedListener 16 ViewChangedEvent 16 ViewChangedListener 16 Examples directory 439

e.Spreadsheet application 5 HTML 7 of chart sizing attributes 394 of tags 379 servlet code 439 Examples directory 23 Examples folder xxii Excel 8/9 (Office97/2000) file format 323 compatibility and limitations 169 formats supported 434 compatibility issues document 438 excel_compatibility.html file 438 exporting to 112 formatted cells limitation 170 writing to Excel 8/9 (Office 97/200) format 231, 237 Exceptions 15 Exporting worksheets 112 External data, See Data External references, accessing 103 Extras Installation Pack 181

F
f1 tag prefix 378 f19api.chm file 438 f19designing.chm file 440 f19designing.pdf file 440 f19functions.chm file 440 f19functions.pdf file 440 f19help.chm file 440 f19jsp.chm file 440 f19jsp.pdf file 440 f19programming.chm file 440 f19programming.pdf file 440 f1help.jar file 10, 439 f1j_ide.html file 438 F1J9.exe file 3, 437 f1j9.ini file 437 f1j9awt.jar file 270, 436 f1j9awtdesign.jar file 437 f1j9swing.jar file 3, 10, 364, 371, 436 f1j9taglib.jar file 364, 365, 371 f1jtextures.jar file 10, 182, 364, 371, 441 f1taginstall.war file 359, 367

452

Programming e.Spreadsheet Reports

f1tagtest.jsp file 361, 366, 367, 368, 372 F9 key 57 features.html file 438 fieldnames attribute of CreateDataRange tag 385 file attribute of CreateFileDataSource tag 386 File isolation, and the properties file 413 File names and protocols, in the book attribute 375 Files connecting to via data pipes 237 delimited, See Delimited text e.Spreadsheet native file format 271 e.Spreadsheet program 436 Excel compatibility 434 hyperlinking to 144 importing XML using XSLT 255 in JRun shared installation 363 single installation 362 in TomCat shared installation 370 single installation 368 Internationalization 441 positional text 241 reading and writing in e.Spreadsheet 308 refresh options in data source 243 setting encoding method 312 format 310 open password 313 save password 313 type 310 signing JAR 29 size, performance tuning and 52 Fill down formulas 248 filldown attribute of CreateDataRange tag 385 Fixed-width files, See Delimited text Fixing and unfixing rows and columns 128 Floating point 169 Focus getting with one click 189 giving a specific worksheet 122 giving e.Spreadsheet 116 making active cell visible 78 scroll bar gaining 132

Font attributes, getting and setting 161 color, setting 162 maximum number per sheet 434 Fonts as conditional formatting 146 changing 160 default, making scale proportionally 162 in headers and footers 124, 347 scaling proportionally with TrueType 162 setting default font 117 Footers, See Headers and footers Forcing Enter key to move to next row 78 methods to fire 190 no zero values 167 one-click action on object 189 user to delete values only 80 user to select unprotected cells 82 ForEachDatapoint tag 377, 388 examples of 379 ForEachLegend tag 377, 389 examples of 379 ForEachSeries tag 377, 389 examples of 379 Format Cells dialog, adding format to 156 formatmode attribute of CreateDataRange tag 385 Formatting 107170 adding custom number format 156 avoiding in blank cells 52 cell borders 112 cells 56133 color 134 pattern 135 conditional 146 custom 155 data 142 database data 248 dates 48, 159 in local format 158 demo 24 graphics object color 187 header and footer fonts 347 maximum length of string in cell 434 numbers as currency 156 numbers/values 152157

Index

453

partial cell 142 text areas 179 using XSLT 248 worksheets 108 formula attribute of GetCell tag 391 of GetRange tag 397 Formulas accessing on another worksheet 103 filling down adjacent to range 248 for incrementing dates 89 getting results on a web page 294, 297 getting row and column reference 66 getting text value of 96 information and garbage collection 54 maximum length 434 naming 101 number of parameters (max) 59, 434 returning result as text or number 142 Freezing panes 128 function_readme.html file 438 Functions add-in 1822 CONCATENATE 19 e.Spreadsheet reference xxiii IF 167 ISERROR 167 number of arguments or characters 59 number of in e.Spreadsheet 434 OFFSET 166 setting recalculation for add-ins 22 SUM 18, 20 TEXT 167

G
Garbage collection and defined names 103 calling to free memory 353 increasing or decreasing 54 using destroy with named groups 119 using the gc method 54 General, setting number format to 152 GetBook tag 390 examples of 379 property keys for 414 GetCell tag 390

defaults for 411 examples of 379 property keys for 414 GetChart tag 391 defaults for 411 examples of 379 property keys for 414 GetRange tag 397 defaults for 411 examples of 379 property keys for 414 Getting major article 96 #DIV/0 errors 424 active cell position in coordinates 77 an object's ID number 187 best performance from e.Spreadsheet 51 cell contents from relative cell location 166 data type 97 column header height 123 column width in twips 130 data being entered in a cell 47 defined name use and location 98 different types of data 58 font attributes 161 formula reference 66 formula results on an HTML page 294, 297 header text 123 ID number of button clicked 43 information from object event parameters 192 invalid argument error 68 length of blob object 319 location string 98 locks 53 number of defined names in use 103 elements in a byte array 319 sheets in workbook 108 numbers instead of text 167 object ID number from name 192 in dropdown list box 195 location 183 name from ID number 192 page from local hard drive 188

454

Programming e.Spreadsheet Reports

previous value in a cell 98 print area information 341 range reference of selected cells 66 range to twips 169 row and column coordinates 69 row and column references 66 row header width 123 row height 169 screen position 77 text as the user sees it 164 instead of numbers 167 of a formula 96, 142 current cell 96 referenced cell 96 type of file read in using readFromBlob 318 user information 4550 value of a formula 142 version number 22 visible rows 128 when active cell or sheet changes 48 which key is pressed 47 worksheet name 111 x, y coordinates of a cell 184 zero instead of an error message 167 GIF images 394 GIF, writing chart images as 330 global.properties file, in JRun 365 Gradient patterns 181 Graphics 171196 See also Objects Graphics emulation package, for JSP Charting API 357 Greater-than symbol (>) 263 Gregorian calendar 88 Gridlines hiding 112 included in result from rangeToTwips 169 using draw to print without 201 width added in rangeToTwips 169 Grouping radio buttons 178 workbooks 119 GUI deploying without one 292

problems converting from JBook 428 using with setColWidthAuto 431

H
Hardware, for JSP Charting API 357 Headers and footers font style formatting 347 font, setting 124 getting and setting text 123 multiple-line data in 126 printing row and column 346 printing with draw 350 reverting to default 126 height attribute chart sizing and 394 of GetChart tag 392 of InsertChart tag 399 Help additional help sources 23 demos 23 f1help.jar 4 running with e.Spreadsheet Designer 4 Hiding See also Displaying cell value 143 columns without hiding objects 190 formulas that return 0 167 gridlines 112 part of the worksheet 85 print dialog 340 rows and columns 127 type markers 139 using setHidden 143 using setVisible 37 worksheet tabs 112, 121 worksheets 37 Highlighting an entire row 83 HTML code example for amortization servlet 288 code examples 7 Converter utility 7 converting worksheet data to using XML/ XSLT 325 embedding worksheets in 270 example accessing the API using JavaScript 302

Index

455

example using <java> tags 294, 297 formatting charts in using XSLT 330 HTML Converter plug-in 271, 302 HTMLWriter class 272, 290 using write to save as 272 html.xsl file 422 Hyperlinking 143

I
iDatapointCount[0] variable of ForEachDatapoint tag 377, 388 iDatapointPosition[0] variable of ForEachDatapoint tag 377, 388 If condition errors 425 iGetRangeColumnCount[0] variable of GetRange tag 377, 398 iGetRangeRowCount[0] variable of GetRange tag 377, 398 iGetRangeSheetCount[0] variable of GetRange tag 377, 398 iLegendCount[0] variable of ForEachLegend tag 377, 389 iLegendPosition[0] variable of ForEachLegend tag 377, 389 Image maps, chart inserting with InsertChart tag 399 inserting with InsertChartImageMap tag 401 variables for 377 XML output schema for 420 imagemap.xsl file 422 Images adding to worksheets 172 backgrounds threads for production of 418 compression technologies 330 disk space for 418 memory for 419 textures for backgrounds 181 using as graphics objects background 182 writing charts as imagemaps 330 Importing data See Data large blocks of information 91 XML using XSLT 255

index attribute of SetDataQueryParameter tag 408 Index numbers 108, 122 InfoBus 437 infobus.jar file 437 Initiating edit mode 87 input functions and statements See file input/ output functions and statements Input/Output 307337 InsertCell tag 398 defaults for 411 examples of 379 property keys for 414 InsertChart tag 399 defaults for 411 examples of 379, 414 property keys for 414 XML output from 420 InsertChartImageMap tag 401 defaults for 411 examples of 379 property keys for 414 XML output from 420 InsertDebug tag 402 context parameter for 418 examples of 379 Inserting carriage returns 138, 347 cells 64 columns 64 data 75 dropdown list boxes 193 images 172 multiple VTS files 316 protected ranges 81 ranges 64 rows 64 sheets 108 tab-delimited text strings 323 using the insertItem method 193 insertmode attribute of CreateDataRange tag 385 InsertRange tag 403 defaults for 411 examples of 379, 414 property keys for 414 XML output from 420

456

Programming e.Spreadsheet Reports

InsertVersion tag 405 examples of 379 Installing e.Spreadsheet ??441 Installing online documentation xxiv Instantiating 8 Integer array, sets positional text breaks 241 Interfaces Book 275 BookModel 292 CancelEditListener 46 ChartModel 12 Constants 12, 17 DatabaseQueryParamCollection 209 DatabaseQueryParameter 209 DataRange 209 DataRangeCollection 209, 229, 246 DataRangeFormatIterator 210 DataRangeIterator 210 DataSourceCollection 210, 212, 229, 246 EndEditListener 46, 117 ImageCompressionIF 336 Model 12 ObjectListener 190 SelectionChangedListener 48, 174 Source 211, 229 StartEditListener 46, 82, 117 International See also e.Reporting for Multiple Locales displaying dates in local format 158 Internet deploying e.Spreadsheet over 2737, 270 285 links for more information 435 Internet Client SDK 33, 35 Internet connection for JSP Charting API 357 Internet Explorer 271 permission levels 34 preparing applets for distribution on 33 security settings 34 using RSA verification with 30 version 5 36 Intranet connection for JSP Charting API 357 Invalid argument error 68 iSeriesCount[0] variable of ForEachSeries tag 377, 389 iSeriesPosition[0] variable of ForEachSeries tag 377, 389

Italics font formatting 161 font formatting in header 348 Iterations maximum number of 434 setting maximum number of 424

J
JAR files creating 31 signing 32 swingall.jar 37 to include JavaHelp 40 unjarring classes from 33 Java executing a Java class from the Designer 226 Java Security 2837 Java Web Server example 297 Plug-in 8 Properties object 315 tags, Java Web Server example 294 Java 2 (J2SDK) slow screen repaint bug 424 Java code, in tag libraries 356 Java Plug-in 3031, 268, 270, 271, 302 Java Runtime Environment (JRE), for JSP Charting API 357 JavaBeans using e.Spreadsheet as 18 Javadoc 23, 438 JavaHelp 439 including in class path 40 JavaScript 36, 302 javasign.dll 33, 35 JAXP jaxp.jar file 10, 437 version 1.1 compatible parsers 265 JAXP, upgrading in JRun 361 in TomCat 367 JBooks grouping 119 loading dynamically 8 JBuilder 18 See also development environment

Index

457

JDBC databases supported 206 loading in data using 127 result set dataType 256 JDeveloper 18 See also development environment JDK bugs, See Bugs getting version number 22 security under different versions 2831 version 1.1.x and print dialog 340 and print orientation 340 version 1.2 and data orientation 138, 163 and landscape printing 340 and print spooling 354 and screen redraws 424 version 1.3 and print spooling 354 and screen redraws 424 jh.jar file 10, 40, 439 jndi attribute of CreateJDBCDataSource tag 387 JRE (Java Runtime Environment), modifying .properties file in 265 JRun administrative console in 359 directory for shared web applications 364 installing the JSP Charting API in 359 local.properties file 365 shared web application 363 single web application 361 upgrading XML parser in 361 web.xml file in 362, 364, 365 JSP engine 372 JSP Charting API variables in 375 pages, directory for, default 419 web server support of 357 JSP Charting API attributes, see Attributes classes, source of 358 tags, see Tags test web app, see test web app variables, see Variables JVM (Java Virtual Machine)

effects on memory size 56 setting class path on 39, 40 versions and browser compatibility 271

K
key3.db 31 Keys 31 CTRL 77 CTRL + Shift 66 CTRL-C 76 CTRL-V 76 Delete 80 Enter 78 F9 57 Return 78 keytool 29

L
Landscape page orientation 340 Languages, deploying in, See Translations Large numbers, displaying 157 legend attribute of InsertChart tag 401 of InsertChartImageMap tag 402 legendurl attribute of InsertChart tag 401 of InsertChartImageMap tag 402 Less-than symbol (<) 263 Limiting number of characters entered 84 selection range 83 visible worksheet area 85, 116 Limits 434 Line constant to separate lines of text 138 Lines adding with addObject 173 drawing with setMode 175 Linking chart to data (example) 174 graphics objects to a cell 176178 listbox to cell 194 Links, list of referenced 435 Linux Redhat 7.0 430 List boxes (drop-down), See Dropdown list boxes Listboxes

458

Programming e.Spreadsheet Reports

adding to worksheet 176 adding with addObject 173 drawing with setMode 175 Listeners, See Events 15 LoadBook tag 375, 405 examples of 379, 413 property keys for 414 Loading data from an array 90 local.properties file, in JRun 365 Localization See also e.Reporting for Multiple Locales 158 default 158 for user input 158 formatting numbers 152 Location isolation, and the properties file 414 Locking and unlocking cells 8182, 139 views and workbooks 53 Look and feel, changing 109 LZW image compression 330

M
Main method, using e.Spreadsheet in 9 Manuals directory xxiv Maximums 434 Memory and printing 353 preventing memory leaks 54 reclaiming 103 understanding structure 55 using efficiently 51 merge attribute of InsertRange tag 404 Merge file 212 Merging cells 137 data using a merge (.properties) file 213 using XML 324 Message box, creating 43 Methods addEndEditListener 47, 84, 117 addHyperlink 143 addItem 193 addKeyListener 47 addObject major article 173

adding charts example 176 adding custom GIF example 334 drop-down list box example 193 listbox example 176 positioning checkbox example 188 radio buttons/group example 179 text area example 180 addPicture 172 addPolygon 180 addWindowListener 37 attach 119 cancelEdit 85 cancelEditEvent 46 clearRange 70, 73, 94 copyDataFromArray 90, 91 copyRange 53, 71, 75, 330 delete 254 deleteDefinedName 343 deleteItem 193, 195 deleteRange 73 draw 197, 350 editClear 71, 72, 73, 80 editCopy 71, 75, 89 editCopyDown 53, 89 editCopyRight 53, 89 editCut 73 editDeleteSheets 108 editPaste 76, 81, 90 editPasteSpecial 76 enablePrivilege 36 encode 330 endEdit adding listener 48 canceling user entry example 49 getting edit mode example 46 getting user entry example 47 limiting character entry example 84 resizing view example 117 validation code example 85 endFieldInfo 212 endMetaData 212 endRange 212 evaluate 18 factory 229, 231, 238, 240, 241, 246, 247 filePrint 36, 198, 340, 344, 345 find 209 fitToPage 344, 345, 352

Index

459

forceRecalc 57 formatRCNr 98 gc 54, 353 get 210 getActiveCell 83, 117 getActiveCol 80, 82 getActiveRow 82 getAdvancedConnectionProperties 212 getArgument 20 getArgumentCount 20 getBook amortization servlet example 288 chart example 176 Data Pipes delimited text example 240 move data range example 254 validation example 165 write example 272 getCellFormat major article 161 cell alignment example 140 cell color example 134 cell protection example 81, 82 changing font example 160 currency format example 156 custom number format example 155 format cell example 134 four-digit year example 158 hiding cell value example 143 merging cells example 137 multi-line data example 138 number formatting example 152 returning text example 164 setting header font example 124 setting text color example 162 validation example 165 getChartModel 176 getCodePage 210 getCol major article 69 add-in function example 20 dynamically creating object example 174 getting screen position example 77 limiting selection range example 83 resizing view example 117 using clearRange example 70 getColText 123

getColumnDataFormats 211 getColumnNames 211 getColumnNumber 209 getColWidth 123, 169 getDataHandler 240, 241, 243 getDataQueryCollection 211, 231, 247 getDataRange 254 getDataRangeCollection 231, 247, 254 getDataSourceCollection 231, 238, 240 getDefaultFontName 160 getDefaultToolkit 50, 77, 426 getDefinedName 69, 103 getDelimiters 211 getDescent 198 getEditString 47, 84, 85, 98 getEntry 58, 98 getFileType 310 getFirstObject 316, 330 getFlags 272 getFontColor 161 getFontMetrics 198 getFontName 160, 161 getFontSize 161 getFontSizeInPoints 161 getFormattedText 164 getFormula 58, 96 getGraphics 198 getHeaderHeight 123, 126 getHeaderWidth 123 getID 192 getImageableHeight 198 getImageableWidth 198 getImageableX 198 getImageableY 198 getInitParameter 282 getInitParameterNames 282 getInputStream 282 getItem 195 getJndiName 212 getKeyCode 47, 76, 80 getKeyText 47 getLastCol 67, 69, 322, 323, 342 getLastRow major article 67 comma-delimited text example 323 inserting files example 316 resizing view example 117

460

Programming e.Spreadsheet Reports

setting print area example 342 tab-delimited data example 322 getLeftCol 128, 131 getLock major article 53 and memory use 51 Data Pipes database example 231 Data Pipes merge example 223 Data Pipes positional text file example 241 Data Pipes text file example 237 delimited data file example 240 GUI-less servlet example 293 in Data Pipes 210 in DataRangeImpl 212 JSP example 294 positional text file example 241 servlet example 291 source connection example 238 getMaxCol 68, 81, 123, 129 getMaxRow 81, 123, 129 getMessage amortization servlet example 288 creating applet example 267 creating application example 37 getting screen position example 77 getName 192 getNextObject 316, 330 getNumber 20, 58 getNumSheets 108, 274 getObject 185192 chart image example 330 displaying list box object example 194 dropdown list box example 193 getting object info example 192 selecting object example 185 setting color example 187 setting index value example 186 getOutputStream 291, 293 getParameter 291, 294 getPos 183, 316 getPrintArea 341 getPrinterJob 198 getPrintJob 198 getPrintScale 345, 352 getPrintScaleFitHPages 352 getPrintScaleFitVPages 352

getProperty 112, 274, 330 getQuery 209 getRefreshIndex 211 getRow major article 69 add-in function example 20 dynamically creating object example 174 getting screen position example 77 limiting selection range example 83 resizing view example 117 used with clearRange 70 write example 272 getRowHeight 169 getRowNumber 209 getRowText 123 getScreenResolution 50, 77 getSelectedObject 187 getSelection dynamically creating object example 174 getting cell position example 66 getting row and column coordinates 69 getSheet add-in function example 20 adding charts example 176 Data Pipes example 254 getting changed sheets example 48 getting text value example 96 getSheetName 111 getSource 37 getTabbedText 322, 323 getText 19, 58, 94, 294, 323 getTextQualifier 211 getToolkit 198 getTopRow 128 getType 20, 94, 97, 192, 330 getValue 195 getVersion 22 getVersionString 22 getWorkbookName 103 getX 50, 77, 183, 316 getXSLTDocument database example 229 in data range set up example 247 in delimited text example 240 in file data source example 238

Index

461

in positional text example 241 XML/XSLT example 257 getY 50, 77, 183, 316 initWorkbook 121, 238, 240, 294, 318 insertRange 64 insertSheets 176 isBorder 112 isLocked 82 isTreatConsecutiveDelimitersAsOne 211 JBook converting to BookModel objects 292 formerly View 435 keyPressed 47 keyReleased 47 messageBox 43 mouseClicked 50 move 210, 254 moveRange 166 objectClicked 190, 192 objectDblClicked 190, 192 objectValueChanged 191 rangeToPixels 184 rangeToTwips 128, 169, 184 read 172, 188, 223, 293, 308, 310, 325, 330 readFromBlob 310, 318 readObject 321 readURL 284, 315 recalc 57, 231, 237, 240, 241, 293 refresh 212, 238, 240, 241, 243, 245 registerDataRangeListener 211 releaseLock major article 53 and performance 51 database example 231 delimited data file example 240 GUI-less example 293 in DataRangeImpl 212 merge example 223 text file example 237 used with Data Pipes 210 removeEndEditListener 84 removeObject 187 requestFocus 116, 302 runCopyData 316 saveViewInfo 112 saveWindowInfo 316 selectionChanged 48, 174

setActiveCell 82, 91, 316 setAdjustColWidth 252 setAdvancedConnectionProperties 212 setAllowDelete 80 setAllowDesigner 4 setAllowInCellEditing 316 setAllowMoveRange 84 setAllowObjectSelections 185 setAllowSelections 112 setAutoRecalc 57 setBackground 37 setBorder 112 setBounds 8, 316 setCanceled 49, 80, 82 setCell 176, 179, 186, 194 setCellAsText 209 setCellFormat major article 161 automatic format example 48 cell alignment example 140 cell color example 134 cell format example 134 cell protection example 81 changing font example 160 conditional formatting example 149 currency format example 156 custom number format example 155 four-digit year example 158 hiding cell value example 143 multiple-line data example 138 number formatting example 152 returning text example 164 setting cell pattern example 135 setting header font example 124 setting text color example 162 validation example 165 setCellFormattingMode data range example 247 data range set up example 246 database example 229 file data source example 238 file example 238 importing database example 248 positional text example 241 XML/XSLT example 257 setChartType 173 setClip 91

462

Programming e.Spreadsheet Reports

setClipValues 91 setCodePage 210, 309, 312 setColHidden 127 setColOutlineCollapsed 113 setColOutlineLevel 113 setColSummaryBeforeDetail 113 setColText 123, 126 setColumnDataFormat 211 setColumnName 243 setColumnOutlineCollapsed 209 setColWidth 129, 169 setColWidthAuto 117, 127, 129, 155, 428 setColWidthUnits 130, 169 setConditionalFormats 149 setContentType 282, 291, 293 setCreateImageMap 330 setDatabase 231, 247 setDataHandler 229, 238, 240, 241, 257 setDataHandlerType 231, 247, 257 setDataPipesOverrideFile 223 setDataPipesOverrideProperties 213, 315 setDataPositions 241 setDataQuery 210, 211, 230 setDataSource 211, 238, 240, 257 setDataSourceCollection 240 setDefaultFont 117 setDefaultFontName 160 setDefinedName 70, 101, 342 setDelimiters 211, 240 setDocumentPath 231, 238, 240, 241, 247, 257 setDriverName 231, 247 setEnableProtection 73, 81, 127, 139 setEnableRefreshOnFileOpen 244 setEnableSourceRemovalBeforeSave 244 setEnterMovesDown 78 setEntry amortization example 297 amortization servlet example 288 entering dates example 88 entering in a range example 89 returning text example 164 sorting example 94 setFieldLabel 212 setFieldName 212 setFilePath 238, 240, 241 setFileType 309, 310

setFillDownFormulasAdjacentToRange 25 2, 253 setFixedCols 128 setFixedRows 128 setFlags 272, 291, 297 setFont 161, 198 setFontBold 134, 161, 180 setFontColor 134, 137, 161, 162 setFontItalic 134, 161, 180 setFontName 160, 161 setFontOutline 161 setFontShadow 161 setFontSize 161, 180 setFontSizeInPoints 161 setFontStrikeout 161 setFontUnderline 161 setFormula cell protection example 82 chart imagemap example 330 concatenating text example 95 date +1 example 89 defined name example 101 getting text value example 96 JSP example 294 number/text display example 323 referencing external cell example 103 relative reference example 166 returning no error example 167 totaling values example 69 using addObject example 173 setFormula1 147 setFormula2 147 setGroup attaching workbooks example 119 loading worksheet example 284, 315 referencing external cell example 103 setHeaderHeight 123, 126 setHeaderSelection 66, 124 setHeaderWidth 123 setHidden 143 setHorizontalAlignment 140 setHyperlinkBase 143 setImageMapDefaultUrl 330 setImageMapName 330 setIncludeFieldNames 252 setIncludeRowNumbers 252 setInsertMode 244

Index

463

setItem 193 setIterationEnabled 424 setIterationMax 424 setIterationMaxChange 424 setJndiName 212 setLayout 37, 267 setLeftCol 78, 131 setLength 19 setLinkRange 173, 176, 330, 334 setLocked 81 setLookAndFeel 109 setMaxCol 68, 85, 116 setMaxRow 85, 116 setMergeCells 137 setMergeRangeType 325 setMinCol 68, 85, 116 setMinRow 85, 116 setMode 173, 175 setMultipleSelections 176 setName 188, 190, 192 setNumber 88, 94, 128 setNumSheets 108, 122 setOpenPassword 309 setOperator 149 setOrientation 78, 163, 198 setPassword 231, 309 setPattern 134, 135, 181, 184, 187 setPatternBG 134, 135 setPatternFG 135 setPatternURL 181 setPos 184 setPrint 345 setPrintable 197 setPrintArea 342, 344 setPrintColHeading 198, 346 setPrintFooter 347, 349, 353 setPrintGridLines 198, 201 setPrintHeader 347, 349, 353 setPrintLandscape 340 setPrintNoColor 343 setPrintRowHeading 198, 346 setPrintScale 343, 344, 345, 352 setPrintScaleFitHPages 341, 345 setPrintScaleFitToPage 341, 343 setPrintScaleFitVPages 341 setPrintTitles 349, 350 setQuery 231, 236, 247

setReferenceArgument 20 setRefreshIndex 211 setRepaint 51 setReturnValue 19, 20 setRowHidden 127 setRowMode 83 setRowOutlineCollapsed 209 setRowOutlineLevel 113 setRowText 123, 126 setSelection cell color example 134 cell protection example 81 entering in a range example 89 inserting files example 316 limiting selection range example 83 merging cells example 137 non-contiguous selections example 77 selecting object example 185 setting cell pattern example 135 sorting data example 94 using addObject example 173 validation example 165 write example 272 setSheet 108, 112, 122, 176, 316 setSheetName 122 setSheetSelected 111 setSheetType 176 setShowColHeading 125 setShowEditBar 8, 302 setShowFormulas 142 setShowGridLines 112, 201 setShowHScrollBar 132 setShowRowHeading 125 setShowSelections 112, 189 setShowTabs 121, 122 setShowTypeMarkers 139 setShowVScrollBar 132 setShowZeroValues 167 setSize 37, 267 setStartRow 240, 241 setTableName 212 setText creating applet example 267 creating application example 37 format cell example 134 getting key pressed example 47 hiding cell value example 143

464

Programming e.Spreadsheet Reports

multiple-line data example 138 number/text display example 323 printing with draw example 198 radio button example 179 resizing view example 117 sorting example 94 text area example 180 using blob methods example 318 write example 272 setTextQualifier 211 setTitle 37, 173 setTopLeftText 123 setTopRow 78, 131 setTreatConsecutiveDelimitersAsOne 211 setType 149 setUserName 231 setValidationRule 165 setValueFormat 88, 152, 156, 157, 164 setValueFormatLocal 156, 158 setVerticalAlignment 140 setViewScale 116 setVisible 37, 267, 316 setWordWrap 138 setWorkbookName 103 setWriteFormatAttributes 325 setWriteKeyAttributes 325 showActiveCell 78 sort 92, 94 sort3 92 startEdit 46, 80, 87 startFieldInfo 212 startMetaData 212 startRange 212 twipsToRC 50, 77 unregisterDataRangeListener 211 View, (now JBook) 435 write amortization example 297 amortization servlet example 288 as Excel 2000 example 323 as HTML example 272 comma-delimited example 323 database connection example 231 exporting worksheet example 112 GUI-less servlet example 293 in e.Spreadsheet 308 inserting images example 172

output stream example 320 tab-delimited example 322 text file connection example 237 types deprecated 310 using constants example 17 using merge file example 223 using with Plug-in 36 with ChartImageEncoder 331 with htmlWriter 297 with XMLWriter 324 writeFile 282 writeImage 334 writeImageMap 330 writeObject 321 writeRLEGIF 330 writeToBlob 310, 318 writeURL 274284 servlet 282 types deprecated 310 Microsoft Access, supported databases in Data Pipes 206 Excel, See Excel Internet Explorer, See Internet Explorer Office compatibility 434 website for downloading Internet Client SDK 34 Microsoft Excel files 375 Minimums 434 Model, accessing underlying spreadsheet 96 Model-View-Controller pattern 294 Moving data ranges in data pipes 253 information (methods for) 91 large amounts of information 91 worksheet tabs 121 Multi-homing environment in JRun 360 Multiple-line print headers 349

N
Naming cells, values, and formulas 101 e.Spreadsheet objects in HTML 303 graphics objects 176181 maximum length and number of names 434

Index

465

range values, making absolute 70 worksheets 122 Native file format 271 Netscape Navigator compatibility 271 digital signatures and 31 preparing applets for distribution on 33 using RSA verification with 30 Netscape Signing Tool 30, 31 New line character (/n) 349 Number format, general 152 Number formats, and InsertCell tag 398 Numbers adding custom format 156 custom formatting 155 formatting 152157 formatting as currency 156 largest, smallest, positive, negative 434 making positive numbers black 152 precision in e.Spreadsheet 434

O
Object Input stream 321 signing certificate 30 tags 8, 271 Objects adding with addObject 173 charts 176 creating dynamically 174 custom polygon 180 deleting during runtime 187 forcing methods to fire for 190 getting location of 183 graphics 171196 ID number, getting 192 listboxes 176 making smaller than the cell 190 making transparent 184, 187 name, getting 192 naming 101 preventing users from moving 185 radio buttons 178 ReadParams and WriteParams 308, 310 selecting 185 serializing 321

setting backgrounds for 181 setting colors for 187 text areas 179 type, getting 192 OFFSET worksheet function 166 Online documentation xxiv, 10 Online reports xvi Oracle supported databases under data pipes 206 Order of entries properties file and 410 web.xml file and 417 Orientation, text 163 Outlining worksheets 113 Output HTML 272 imagemap 330 number value vs text 323 writing charts as images 330 writing to a BLOB or byte array 318319 writing to a URL 274 writing to an output stream 172, 274, 282, 320 writing to Excel format 231, 237 XML 330 Ovals adding with addObject 173 drawing with setMode 175 Overriding attribute values 412 defaults and 412 redefined values and 412

P
Packages addin 12 calc 12 chart 12 data 12 infobus 12 mvc 12 ss 13 swing 13 swing.designer 13 swing.ss 13 util 13 Packages, API in e.Spreadsheet 12

466

Programming e.Spreadsheet Reports

Page setup attributes, changing 345 PARAM name attribute settings 284 Parameters See also Constants e.Spreadsheet 225 maximum number in formula 59, 434 Parsers compatible with e.Spreadsheet 263 password attribute of CreateJDBCDataSource tag 387 Pasting 7476 making shortcut key for 76 multiple VTS files in same workbook 316 protected cells 81 the same value in all cells in a range 89 values only 76 with CTRL-V keys 76 Patterns gradients and textures 181 setting for cells 135 support under Java 2 182 using custom background 181 PDF files xxiv Performance advantages of using VTS files 271 background thread 54, 59 data structure and memory size 55 garbage collection 54 getting and releasing locks 53 memory leaks and printing 353 reading-in data 58 using memory efficiently 51, 55 Permission levels 3435 Pictures adding with addObject 173 drawing with setMode 175 Pixels converting to twips 50 getting cell location in 184 gridline width in 169 PJA Toolkit 430 PNG images 394 PNG, writing chart images as 330 Point array 55, 180, 241 Point object, setting x and y values for 180 Polygons adding with addObject 173

creating custom 180 drawing with setMode 175 Populating variables 376 Portrait page orientation 340 Positional text, See Delimited files Prefix, for tags defining 378 using 373 Preventing data entry 82 dates in the wrong format 159 formulas from returning 0 values 167 memory leaks 54 methods from returning errors 68 methods from setting to true 316 numbers interpreted as text 323 objects from disappearing 190 patterns from printing 343 print area cut-off 354 print jobs from creating memory problems 354 repainting 53 tabs from reappearing 121 the e.Spreadsheet Designer from launching 4 users from changing row/column height/ width 127 entering more than x characters 84 moving cells 84 moving objects 185 switching between sheets 112 using drag/drop 84 value format from changing 48 Print titles, setting 349 Printing 339354 and memory usage 353 clearing print area prior to 342 column and row headings 346 files without using the Plug-in 36 fit-to-page 341, 343344 fit-to-page horizontally 345 fit-to-print 343344 from an applet 36 getting print area information 341 headers and footers 347 headers and footers using draw 350

Index

467

in black and white 343 landscape orientation 340 multiple-line headers 349 page setup attributes 345 portrait orientation 340 preventing print area cut-off 354 print scale 343344 print titles 349 row and column titles 350 suppressing the print dialog 340 user-defined print area 340 using absolute vs. relative range references 342 draw ??201, ??201 filePrint 340 getPrintScale and setPrintScale 352 setPrint and associated methods 345 Private security key 29 Programming e.Spreadsheet Reports xxiii, 440 Programming e.Spreadsheet Web Applications (publication) xxiii, 440 Properties file 409 advantages of using 409 attributes used by more than one tag and 411 changing Data Pipes settings using 212 changing parsers using 265 default attribute values in 411 default, in TomCat 371 e.Spreadsheets 416 settings in 417 using 416 location of in JRun shared installation 364 in JRun single installation 362 in TomCat shared installation 370 in TomCat single installation 369 name of, setting 419 overriding attribute values in 412 redefining attribute values in 413 structure of 410 using {filename}.txt 239 using {mergefile.dir} 213 Property keys 410 list of 414

Property values 410 Protection, setting for cell 81, 139 file 314 sheet 313 workbook 314 Public security key 29

Q
Queries database, using data pipes 236 database, using datapipes 209 query attribute of CreateDataQuery tag 382

R
Radio buttons adding to a worksheet 173, 178 drawing with setMode 175 grouping 178 Range basing a chart on 393, 400 importing data into 384 inserting in JSP page 403 retrieving into a JSP variable 397 setting in a workbook 408 range attribute of CreateDataRange tag 384 of GetChart tag 393 of GetRange tag 397 of InsertChart tag 400 of InsertRange tag 403 of SetRange tag 408 Ranges absolute vs. relative 342 building from lower right-hand corner 52 converting to XML data 324 copyRange 51, 75 formatting blank 52 hyperlinking to 143 inserting 64 maximum number of selected 434 moveRange 51 setting validation rules for 165 Reading files efficiently with VTS format 271 from a URL 274284

468

Programming e.Spreadsheet Reports

from an applet 36 in byte array form 318 in e.Spreadsheet 308 in serialized form 321 without using the Plug-in 36 Readme 23, 438 Recalculations automatic 57 setting maximum number of 424 Rectangles adding with addObject 173 drawing with setMode 175 Redefining attribute values 413 overrides and 412 refresh attribute of CreateDataRange tag 384 RefreshData tag 406 examples of 379 Refreshing data 243, 245 Refreshing external data 384, 406 Relative paths, in the book attribute 375 Relative reference OFFSET function 166 ranges 70 setting print area 342 setting print titles 349 validation 165 Releasing locks 53 reload attribute of LoadBook tag 405 Repainting disabling to improve performance 51 slow running under Java 2 424 ReportCast channels xviii, xix Reporting solutions xvi Reports callback classes and 228 Requirements for installing JSP Charting API 357 Resetting options to default using initWorkbook 121 Restrictions, setting user 8085 result attribute of CreateDataQuery tag 382 of CreateFileDataSource tag 386 Return key 78 RLE image compression 330 Root directory for test web app in JRun 360

in TomCat 367 Row coordinates 69 determining last to contain data 67 getting reference 66 getting/setting header size/text 123 headers, reverting to default 126 headings, printing 346 height, maximum and minimum 434 multiple-line data in headers 126 reference array 55 selecting entire for print titles 349 setting first displayed 131 setting top-most displayed 131 showing headings 125 rownumbers attribute of CreateDataRange tag 385 Rows and memory size 55 building worksheet 52 filling worksheets by vs. columns 54 fixing and unfixing 128 getting number of visible 128 hiding 85, 127 inserting 64 maximum number in a worksheet 434 printing titles 350 protecting 81 selecting headers 66 shifting after delete 73 using getRow 69 RSA Verification and applets 30

S
Saving Windows settings 112 Saving as delimited text 323 Excel 8/9 (Office97/2000) 323 HTML using write 272 VTS file 271 SAX parser 263 Saxon XSLT processor 264 scale attribute chart sizing and 394 of GetChart tag 392

Index

469

of InsertChart tag 400 Scientific notation, displaying large numbers in 157 Scope of variables 376 Screen flashing, minimizing 51 Screen position, getting 77 Scroll bar 132 Security Java Security 2837 certificates 29 common errors when implementing 36 digital signatures 29 error 35 Java 2 and 29 levels and RSA Verification 30 policies 29 public and private keys 29 setting levels 29 settings for Internet Explorer 34 Select, SQL query command 236 Selected ranges, maximum number of 434 Selecting multiple ranges 77 Selecting objects See also object graphics 185 using setSelection 185 with one click 189 Serializing an object 321 series attribute of InsertChart tag 401 of InsertChartImageMap tag 402 seriesinrows attribute of GetChart tag 393 of InsertChart tag 401 seriesurl attribute of InsertChart tag 401 of InsertChartImageMap tag 402 Server name, for installing in JRun 360 requirements for JSP Charting API 357 Servers xix Server-side deployment 287303 Servlet WAR file, in JRun 360 Servlets creating 288 creating GUI-less 292 demos, finding xxii

used with writeURL 275 using the writeURL servlet 282 Servlets, example code and directory for 439 Servlets, setting directory for 419 SetCell tag 407 examples of 379 property keys for 414 SetDataQueryParameter tag 407 examples of 379 SetRange tag 408 examples of 379 property keys for 414 Setting a point object's x and y values 180 backgrounds for graphics objects 181 cell background color 134 index value 186 pattern 135 protection 139 code page type 310 column header height 123 column width 129 conditional formats 146 data source refresh options 243 date formats 88 default font 117 defined names as relative or absolute 70 display scale 116 first row or column displayed 131 focus to a sheet 108 font attributes 161 header and footer font formatting 347 header font 124 header text 123 Internet Explorer permission levels 34 levels of security 29 look and feel 109 number format 152157 number of sheets 108 object color 187 object index value 186 options to defaults 121 page orientation 340 page orientation using draw 341 page setup attributes 345 PARAM name attributes 316

470

Programming e.Spreadsheet Reports

permission levels 33 print area 342 print scale 341, 343, 344, 345, 352 print titles 349 printing to black and white 343 protection for files 314 ranges 81 workbooks 314 worksheets 313 resetting header to default 126 row header width 123 row mode status 83 security policies 29 sheet type 109 text color 162 text orientation 163 type markers 139 user restrictions 8085 validation rules 165 value for list- or checkbox object 191 value format 152157 worksheet area displayed 131 worksheet tabs 121 Shared web applications in JRun 363 directory for 364 incompatible with single applications 363 testing 364 in TomCat 369 directory for 371 incompatible with single applications 369 testing 370 Sheets, See Worksheets Shifting rows and columns after delete 73 Showing, See Hiding, Displaying signcode.exe 3335 Signed applet 30 Significant digits, displaying more than 15 169 signtool.exe 3031 SilverStream 18 See also Development environments Software publishing certificate 31 Solaris

changing class path on 39 launching the e.Spreadsheet Designer on 3 Sorting 9295 dates or numbers with formatting 94 including a blank cell 94 using 3 keys 93 source attribute of LoadBook tag 405 Space required by JSP Charting API 357 Specifications 434 spreadsheetformat attribute of InsertRange tag 404 SQL query commands using data pipes 236 supported database 229 SQL query 382 startrow attribute of CreateDataQuery tag 383 of CreateFileDataSource tag 387 Stored procedures in databases 382 storedprocedure attribute of CreateDataQuery tag 383 strDatapointCoordinates variable of ForEachDatapoint tag 377, 388 strDatapointName variable of ForEachDatapoint tag 388 strDatapointValue variable of ForEachDatapoint tag 388 strGetCellFormula variable of GetCell tag 391 strGetCellText variable of GetCell tag 391 strGetChartCoordinates variable of GetChart tag 393 strGetChartURL variable of GetChart tag 393 strGetRangeFormula2[][] variable of GetRange tag 398 strGetRangeFormula3[][][] variable of GetRange tag 398 strGetRangeText2[][] variable of GetRange tag 397 strGetRangeText3[][][] variable of GetRange tag 397 String symbol ($) 70, 342, 349 strLegendCoordinates variable of ForEachLegend tag 377, 389 strLegendName variable of ForEachLegend tag 389

Index

471

strSeriesCoordinates variable of ForEachSeries tag 377, 390 strSeriesName variable of ForEachSeries tag 389 Stylesheet, XSLT example 232 swingall.jar 37 Symbols See also Symbols (first category in index) displaying > and < as text 263 number formatting 152 Synchronized modifier 19 Syntax conventions (documentation) xxviii System requirements for JSP Charting API 357

T
Tab-delimited text, See Delimited text table attribute of InsertRange tag 404 Tabs displaying a different file on each 316 preventing at runtime 121 showing/hiding 121 Tag library 356 Taglib directive 377 Tags applet accessing API with JavaScript using 303 ARCHIVE 35 CODE 270 attributes, see Attributes converting applet to object or embed 271 embedding Java code inside Java tags 301 HTML exportable format 272 names of 373 output using ChartImageEncoder 331 output using XMLWriter 324 prefix 373 replacing Java with JSP 294 structure of 372 variables, see Variables with bodies 374 without bodies 374 XML conditional formatting 262 XML conversion for e.Spreadsheet 257 Test web app

in JRun for shared web application installation 363 for single web application installation 362 installing 359 testing 361 in TomCat for shared web application 370 for single web application installation 368 installing 366 testing 367 overview 357 uses of 356, 358 Testing in JRun shared installation 364 test web app 361 in TomCat shared installation 370 test web app 367 Text concatenating 19, 95 delimited, See Delimited text getting from a cell 164 maximum length 434 orientation 163 setting color 162 value 96 Text areas (text boxes) adding 179 adding with addObject 173 drawing with setMode 175 text attribute of GetCell tag 391 of GetRange tag 397 TEXT function errors 167 Texture patterns 181 Thawte 30, 31, 32, 34, 435 Threading AWT event on Unix 428 example of efficient 19 multi-threaded servlet example 282 safety 19 TLD file 378 configuring JRun and 362, 364

472

Programming e.Spreadsheet Reports

configuring TomCat and 369, 370 copying, in TomCat shared installation 370 To 112 TomCat default properties file 371 directory for shared web applications 371 installing the JSP Charting API in 366 shared web application 369 single web application 368 upgrading XML parser in 367 web.xml file in 368, 370 Translations full 441 Troubleshooting 423424 missing files errors 39 Troubleshooting with the test web app 358 Truncating title and heading rows 383, 387 tu_2_swing.pdf file 441 Tutorials 23 Twips converting to pixels 50 getting cell location in 184 getting column width in 130 gridline width in 169 type attribute of GetChart tag 393, 400 of SetDataQueryParameter tag 408 Type markers, setting 139 Typographical conventions xxvii

U
Unicode byte order mark 312 Uninst.isu file 437 Uninstalling e.Spreadsheet 437 Unisys 330 Unix 428431 adding a Netscape directory on 31 changing class path on 39 DISPLAY variable 428 e.Spreadsheet compatibility with 428 launching the e.Spreadsheet Designer on 3 replacing : with ; in code 40 running without X-Windows 429

using with e.Spreadsheet and a graphics device 428 X server 429 UNIX requirements for JSP Charting API 357 Unjarring classes from JAR file 33 UnloadBook tag 408 examples of 379 Update information xxii Upgrading XML parser in JRun 361 in TomCat 367 URI, taglib in JRun shared installation 363 single installation 362 in taglib directive 378 in TomCat shared installation 370 single installation 369 URL hyperlinking to 143 list of referenced links 435 of image or pattern used for background 182 of image to insert in worksheet 172 setting data source from 237 setting for data source connection 230 writing to a 274 url attribute of InsertChart tag 401 of InsertChartImageMap tag 402 URL for test web app in JRun 360 user attribute of CreateJDBCDataSource tag 387 Using conditional formatting 146 digital signatures 29 draw to print ??201, ??201 e.Spreadsheet on a server 297 e.Spreadsheet within JSP 294 memory efficiently 51, 55 messageBox 43 readFromBlob and writeToBlob 318 ReadParams and WriteParams objects 308, 310 setLeftCol 131 setPos 184

Index

473

setPrintScale and getPrintScale 352 setTopRow 131 the writeURL servlet 282 VTS files 271 writeURL 274284 UTF-8 and UTF-16 encoding 308

V
Validation rules for number of characters 84 setting for a range 165 value attribute of GetCell tag 391 of GetRange tag 397 Value format 48 Values cutting, leaving formatting 72 naming 101 pasting 76 Values, of attributes 374 Variables 375 for chart imagemaps 377 populated at top of loop 376 scope 376 single-element arrays 376 spelling and capitalization of 375 Verisign 2931 Version number, getting 22 Visual Cafe 18 See also development environment Visual J++ 18 See also development environment VTS files 375 examples containing charts 176 inserting multiple in one workbook 316 loading in embedded applet 315 example 284 returning from local drive with button (example) 188 saving images to 172 writing out as Excel 293

W
Web amortization application example 288 browsers, compatible with LRX xx

deploying e.Spreadsheet over 270285 form that returns user input as HTML data 297 pages, adding worksheets to 270 security issues 28 web page link list 435 Web applications in JRun 361 incompatible with shared applications 363 separate directories for 360 in TomCat 368 incompatible with shared applications 369 shared, see Shared web applications Web servers 372 Apache/JServ 429 installation directories 358 properties file of 409 support for JSP Charting API in 358 Tomcat 430 X11 430 web.xml file context parameters and 417 in JRun in shared installations 364, 365 in single installations 362 in test web app 362 in TomCat in shared installations 370 in single installations 368 in test web app 368 WebLogic, Bea 359 White space, adding without adding memory 51 width attribute chart sizing and 394 of GetChart tag 392 of InsertChart tag 399 Windows changing class path on 39 launching the e.Spreadsheet Designer on 3 saving settings 112 Workbooks adding worksheets to 108 grouping 119 Worksheet functions documentation xxiii

474

Programming e.Spreadsheet Reports

Worksheets building efficiently 51 changing default font 117 name 122 type 109 deselecting 111 displaying within an applet 267 embedding in HTML 270 getting name of active 111 getting when modified 46 giving focus 108, 116 hiding 37 index numbers 108, 122 limiting visible area of 116 loading with embedded applets 284 making active 108 naming 101, 122 optimizing performance of 52 outlining display 113 showing or hiding tabs 121, 122 switching between 112 technical specifications for 434 Wrap text 138 Writing a serialized object 321 charts as image maps 330 comma-delimited text files 323 files from an applet 36 in Excel 2000 format 323 in Excel format 112, 229, 237, 274, 292 in Netscape, no Plug-in 36 SQL queries 236 tab-delimited text files 322 to a URL 274 to an HTML table 272 to an output stream 172, 320, 321, 325, 331 Unicode text files 312 using draw 201 HTMLWriter 272, 297 setClip 91 setClipValues 91 write 17, 36, 112, 229, 237, 272, 290, 300, 308, 316, 320 writeToBlob 318, 319 writeURL 274, 282

XMLWriter 324 worksheet files 312 worksheet files in e.Spreadsheet 308

X
X, y coordinates 77, 173, 184, 198 X11 windows environment 428 Xalan XSLT processor 263 xalan.jar file 10, 437 Xerces parser 264 xerces.jar file 10, 437 XLS files 375 XML converting chart image maps to 420 converting worksheet range to 324, 420 DOM API 209 formatting with 385 importing 255, 382, 386 output from ChartImageEncoder 330 XMLWriter 324 output from InsertChart and InsertChartImageMap tags 420 output from InsertRange tag 420 related JAR files in e.Spreadsheet 10 schemas for 419 tags and attributes table 257, 324 writing a chart image to 330 XML parser, upgrading in JRun 361 in TomCat 367 XMLWriter class 10, 324 XSLT creating a stylesheet to import XML 257 default parser 263 formatting data using 231, 237, 327, 336 related JAR files in e.Spreadsheet 10 stylesheet example 232, 327, 336 using to import XML 255 xslt attribute of CreateDataRange tag 385 of InsertChart tag 401 of InsertChartImageMap tag 402 of InsertRange tag 404 XSLT formatting and cellkeys 404

Index

475

chart imagemaps with 401, 402 external data with 385 viewing built-in document 422 workbook data with 404 Xvfb virtual server 430 X-Windows 429

Y
Year date number formatting 152 formatting date to show four digits 158 function 89 printing four-digit 353

Z
Zero values, hiding 167 Zip file 36 Zooming, using setViewScale 116

476

Programming e.Spreadsheet Reports

Vous aimerez peut-être aussi