Pe SS
Pe SS
Pe SS
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
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
Chapter 3
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 .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
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
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
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
Part 3
Formatting
Chapter 8
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
Chapter 10
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
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
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
Chapter 14
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
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
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
Appendix A
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
xiii
xiv
Intro ductio n
Introduction
xv
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
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
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
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.
xviii
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 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 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
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
XtraGraphics
xxii
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
XtraGraphics
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
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.
xxiv
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
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.
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
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
File FileNew
User input or user response User input in XML and Java code
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
xxviii
Part
1
Part 1
29
30
Chapter
1
Chapter 1
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.
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.
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
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
Code Example
jbook1.setAllowDesigner(false);
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
// 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(); } }
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
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>
</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.
Code Example
The following code dynamically creates an instance of JBook, adds it to a JFrame, and calls the setShowEditBar method.
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){ }
Code Example
static com.f1j.swing.JBook jbook1 = new com.f1j.swing.JBook();
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
10
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
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.
com.f1j.swing
com.f1j.swing.designer
com.f1j.swing.ss
com.f1j.util
13
com.f1j.swing.designer.Designer
com.f1j.util.Group
14
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.
15
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
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);
17
18
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); }
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
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()); }
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
// 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);
21
return; } } fc.setReturnValue(sum); }
Code Example
Example 1: This example returns the version information (version and build number, copyright notice, etc.) in a String format:
jbook1.getVersionString();
22
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.
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
25
26
Chapter
2
Chapter 2
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
27
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.
28
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.
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
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.
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
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
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).
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:
31
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
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.
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,
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.
34
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
where: cab_name.cab is the name of the CAB file you want to check.
35
Security errors:
Either the file is not properly signed or you have not included the extra PrivilegeManager information for Netscape in your code.
Before the call to the filePrint method, you need to add this line:
PrivilegeManager.enablePrivilege("UniversalPrintJobAccess");
36
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();
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
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.
7 Add any other JAR files needed to run e.Spreadsheet or delete any unneeded files. 8 Choose Set. 9 Choose OK.
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.
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.
2 Add any other JAR files needed to run e.Spreadsheet or delete any unneeded files.
40
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.
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
42
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.
43
44
Chapter
3
Chapter 3
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
45
Code Example
void modified(ModifiedEvent e) { m_modified = true; }
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
Code Example
jbook1.addEndEditListener(this); public void endEdit(com.f1j.swing.EndEditEvent edit) { edit.getEditString(); }
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) { } }
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) { } }
Code Example
currentSheet = jbook1.getSheet(); public void selectionChanged(com.f1j.swing.SelectionChangedEvent e1) { int newSheet = jbook1.getSheet(); if (newSheet != currentSheet) { currentSheet = newSheet; } }
48
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) { } }
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(); }
49
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
Chapter
4
Chapter4
Increasing performance
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
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
51
Internet in Chapter 13, Deploying on the Web.Reducing applet and JavaBean size for use over the Internet.
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.
52
This increases the speed of the operation and avoids unnecessary screen flashing.
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.
53
54
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.
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
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
+ 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); }
Code Example
try { jbook1.setAutoRecalc(true); // or jbook1.recalc(); // or
57
// forceRecalc can only be called in the Book interface or BookImpl class book1.forceRecalc(); } catch (com.f1j.util.F1Exception err) { }
58
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.
59
60
Part
2
Part 2
61
62
Chapter
5
Chapter 5
Manipulating cells
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
63
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
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) { }
65
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);
Code Examples
Example 1:
66
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
* 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.
67
Code Example
jbook1.getLastRow(); jbook1.getLastCol();
Code Example
jbook1.setMinCol(arg); // where 0 <= arg <= jbook1.getMaxCol()
68
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) + ")");
69
Making named range values constant regardless of active cell pointer location
To make the values constant, make the references absolute using the $ symbol.
Code Example
jbook1.setDefinedName("dn", "$F$4:$H$10"); // Use absolute references
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
Parameter
Code Example
jbook1.clearRange(jbook1.getRow(), jbook1.getCol(), jbook1.getRow() + 100, jbook1.getCol() + 10, 3);
Code Example
See Copying and pasting data on page 75.
Syntax
public void editClear(short clearType)
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);
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
Code Example
jbook1.editCut();
Code Example
try { jbook1.setEnableProtection(true); jbook1.clearRange(1, 1, 7, 1, jbook1.eClearValues); } catch (com.f1j.util.F1Exception ie) { }
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) { }
74
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
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) { }
75
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
Code Example
jbook1.editPasteSpecial(JBook.eCopyValues);
76
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.
Code Example
This code example selects three separate non-contiguous ranges.
jbook1.setSelection("A1, B2:B4, C5");
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) { } }
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.
78
Code Example
jbook1.setEnterMovesDown(true);
79
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) { } }
Code Example
First, pass false to setAllowDelete.
jbook1.setAllowDelete(false);
80
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);
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.
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.
82
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
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) { }
Code Example
jbook1.setRowMode(true);
83
Disabling drag-and-drop
Calling the setAllowMoveRange method with false effectively disables dragand-drop, making it unavailable to the user.
Code Example
This code prevents the user from moving a range.
jbook1.setAllowMoveRange(false);
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
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
Code Example
public void endEdit(com.f1j.swing.EndEditEvent e1) { if (! e1.getEditString().startsWith("=")) jbook1.cancelEdit(); }
85
86
Chapter
6
Chapter 6
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
87
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)
88
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");
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)");
89
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) { }
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
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);
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
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.
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) { }
93
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");
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
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.
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);
95
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
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) { }
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).
97
Code Example
try { String strPrev = jbook1.getEntry(); } catch (com.f1j.util.F1Exception e1) { }
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) { }
Code Example
int iRow = 0, iCol = 0; boolean bolCellRefType = false; String strTest = jbook1.formatRCNr(iRow, iCol, bolCellRefType);
98
99
100
Chapter
7
Chapter 7
Referencing cells
Syntax
public void setDefinedName(java.lang.String name, java.lang.String formula, int row, int col)
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");
102
Code Example
This code example sets the sheet level name mysheetname to cell $A$1.
jBook1.setDefinedName("Sheet1!mysheetname", "$A$1")
Code Example
if (jbook1.getDefinedName("Test1").compareTo("") == 0){ }
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.
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
Part
3
Part 3
Formatting
Part 3, Formatting
105
106
Chapter
8
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);
Code Example
jbook1.setNumSheets(2); jbook1.setSheet(1);
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
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);
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.
Syntax
public void setHiddenState(short hiddenState)
Parameters
Parameter hiddenState Description a flag indicating the sheet display status:
110
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():
Code Example
This code returns the name of the active sheet.
String mySheet = jbook1.getSheetName(jbook1.getSheet());
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
111
Syntax
public void setBorder(Boolean border) public boolean isBorder()
Code Example
jbook1.setBorder(false); // Sets the border to false
Code Example
jbook1.setShowGridLines(false); jbook1.saveViewInfo(); jbook1.write(System.getProperty("user.dir") + java.io.File.separator +
112
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.
Syntax
public void setColOutlineLevel(int col1, int col2, int outlineLevel, boolean additive)
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
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.
115
Code Example
jbook1.requestFocus(); // Gives jbook1 the focus
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) { } }
Code Example
jbook1.setViewScale(200); // Set the view scale to 200%
116
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);
Code Example
// Implement the com.f1j.swing.StartEditListener and // com.f1j.swing.EndEditListener interfaces and register the classes.
117
jbook1.addStartEditListener(this); jbook1.addEndEditListener(this);
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
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 {
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
Syntax
public void setShowTabs(short showTabs)
Parameters
Parameter eTabsOff eTabsBottom eTabsTop Controls hide tabs tabs on bottom tabs on top
Code Example
This code example sets the tabs to show at the top of the workbook.
jbook1.setShowTabs(JBook.eTabsTop);
121
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.
Code Example
This example sets the name of the first sheet in the workbook to Bob.
jbook1.setSheetName(0, "Bob");
122
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) { }
123
to: Set/get the row header text Set/get the top left header corner text
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) { }
Syntax
public void setHeaderSelection(boolean topLeftHeader, boolean rowHeader,
124
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) { }
125
Code Example
jbook1.setShowRowHeading(false); jbook1.setShowColHeading(false);
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) { }
Code Example
try { jbook1.setColText(0, "This is a \n new line"); jbook1.setHeaderHeight(jbook1.getHeaderHeight()*2); } catch (com.f1j.util.F1Exception err) { }
126
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) { }
127
Code Example
com.f1j.data.DataRange range = book.getSheet(0).getDataRangeCollection().factory("test", 0, 0); range.setAdjustColWidth(false);
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) { }
128
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.
Code Example
try { // Fixes the first two rows and columns jbook1.setFixedCols(0, 2); jbook1.setFixedRows(0, 2); } catch (com.f1j.util.F1Exception err) { }
Syntax
public void setColWidth(int col, int width)
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) { }
130
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);
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();
131
Code Example
jbook1.setShowVScrollBar(jbook1.eShowOn); jbook1.setShowHScrollBar(jbook1.eShowOn);
132
Chapter
9
Chapter 9
Formatting cells
Formatting a cell or range Formatting cells Formatting cell contents Hyperlinking from worksheet cells Using conditional formatting
133
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
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.
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:
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
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.
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); }
138
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);
Code example
com.f1j.ss.CellFormat CellFormat1; CellFormat1 = jbook1.getCellFormat(); CellFormat1.setEnableProtection(true); //Format a range jbook1.setCellFormat(CellFormat1, 0, 0, 0, 0);
Syntax
public void setShowTypeMarkers(boolean)
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);
Syntax
public void setVerticalAlignment(short alignment)
140
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
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);
141
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; }
142
5 Choose OK.
Code Example
jbook1.setShowFormulas(true); // To show formulas jbook1.setShowFormulas(false); // To show values
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");
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
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
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
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 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);
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 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);
146
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
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
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);
149
// Select the range and apply conditional formatting b.setSelection(0, 0, 39, 2); b.setConditionalFormats(condfmt); }
150
Chapter
10
Chapter 10
Formatting data
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
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.
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
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
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
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);
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();
156
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);
Code Example
See code example in Formatting numbers earlier in this chapter.Formatting numbers.
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.
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
158
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
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.
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
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.
161
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.
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
Code Examples
This code example sets the default font to Times New Roman 12 point.
jbook1.setDefaultFont("Times New Roman", 12);
162
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);
Syntax
public void setOrientation(short orientation)
Parameters
Parameter Description
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);
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
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
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);
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
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)");
167
Code Example
jbook1.setShowZeroValues(false); // Dont show zero values
168
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) { }
169
170
Chapter
11
Chapter 11
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
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
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
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);
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
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
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
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.
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
178
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); }
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); }
Syntax
public GRObject addPolygon(double x1, double y1, double x2, double y2, java.awt.Point[] points, boolean closed)
180
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);
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.
182
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);
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
Code Example
java.awt.Rectangle sizeInPixels = new java.awt.Rectangle(); jbook1.rangeToPixels(0, 0, 0, 0, sizeInPixels);
Code Example
com.f1j.ss.GRObject newRectangle = jbook1.addObject(com.f1j.ss.GRObject.eRectangle, 2, 2, 10, 10); newRectangle.setPattern(ePatternNull);
Syntax
public void setPos(double x1, double y1, double x2, double y2)
184
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);
Code Example
// Pass getObject the ID number of the list box. com.f1j.ss.GRObject myobj = jbook1.getObject(1); jbook1.setSelection(myobj);
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
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
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) { }
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
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
Syntax
public void setShowSelections(short ShowFlag)
Parameters
Parameter eShowOff eShowOn eShowAutomatic Description never show always show show when window is active
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
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);
190
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");
Code Example
void objectValueChanged(ObjectEvent e) { try { int i = e.getObject().getValue(); } catch(com.f1j.util.F1Exception e) { } }
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
Code Example
jbook1.getObject(1).setName("Herb"); String n = jbook1.getObject(1).getName();
Code Example
myObject = jbook1.getObject("Herb"); int id = myObject.getID();
Code Example
void objectClicked(ObjectEvent e) { String n = e.getObject().getName(); short s = e.getObject().getType(); int i = e.getObject().getID(); }
192
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) { }
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
Code Example
try { com.f1j.ss.GRObject test = jbook1.getObject(1); test.setItem(2, "Steve"); } catch (com.f1j.util.F1Exception e1) { }
Code Example
try {
194
Code Example
try { com.f1j.ss.GRObject test = jbook1.getObject(1); String s = test.getItem(test.getValue()); } catch (com.f1j.util.F1Exception e1) { }
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
196
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
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
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
TheJob.end(); } } catch (Exception ex) { } } static public void main(String args[]) { DrawToPrinter myPrint = new DrawToPrinter(); myPrint.print(); System.exit(0); }
Code Example
For a code example, see Using draw earlier in this chapter.Using draw.
Code Example
For a code example, see Using draw earlier in this chapter.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
201
202
Part
4
Part 4
Publishing e.Spreadsheet
203
204
Chapter
12
Chapter 12
Introduction and Update Information Setting up a data source Setting up a range Using XML and XSLT
205
206
207
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
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
209
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()
endMetaData startMetaData startFieldInfo() setFieldLabel() endFieldInfo() setFieldName setTableName setFieldLabel setCellHyperlink DataRangeFormatIterator (New API from DataRangeIterator) DataSourceCollection: kDOM
kURL
getCodePage() setCodePage()
210
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()
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()
211
New API (continued) com.f1j.data.source.JDBC getAdvancedConnectionProperties() getJndiName() setAdvancedConnectionProperties(java.util .Properties props) setJndiName(java.lang.String name)
e.Spreadsheet manages locks internally in the DataSourceCollection API when the refresh method is called.
212
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).
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
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
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
215
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>.database
datasource.<name>.user
datasource.<name>.password
datasource.<name>.jndi.name
216
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.
217
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
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
219
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
220
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
221
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.
222
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");
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(); } } }
224
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); }
be located in the Classpath of the machine where it is run. implement the com.f1j.ss.BookModelCallback interface override the callback method
226
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.
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.
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.*;
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(); } } }
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
228
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");
setDataHandlerType method to set the data handler getXSLTDocument method (optional) to set the XSL stylesheet setCellFormattingMode method to set the formatting mode
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.
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
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);
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(); }
232
<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"
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
<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>
235
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.
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
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");
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
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
// 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(); }
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
Code Example
This code example:
s
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
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);
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.
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
This example removes the data source from the file when it is saved.
j_Source.setEnableSourceRemovalBeforeSave(true);
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
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.
246
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");
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();
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
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);
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
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:
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
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);
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
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);
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
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);
257
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
X X X X X X X
258
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
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
259
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
X X X
X X X
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
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.
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" />
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
Code Example
<!DOCTYPE xsl:stylesheet [<!ENTITY lt "<"><!ENTITY gt "?">]>
263
Option 1:
From the command prompt on the server machine.
2 Restart the application. This directs the application to use the Crimson parser found in the class path for the duration of the application.
2 Restart the application. This directs the application to use the Crimson parser found in the class path for the duration of the application.
264
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/.
265
266
Chapter
13
Chapter 13
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
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
269
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
271
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
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
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){ } }
274
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));
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
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.
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.
277
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
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.
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
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
281
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.
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
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());
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
284
PARAM NAME attribute has three settings . The settings are described in the following table.
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>
285
286
Chapter
14
Chapter 14
Deploying on a server
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
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
<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>
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
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("%"))
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"; } }
292
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()); }
293
Code Example
com.f1j.ss.BookModel book1 = new com.f1j.ss.BookModel(); //Initialization book1.initWorkbook();
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
/* * 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>
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
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">
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
<!--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>
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
* 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);
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>
302
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>
303
304
Part
5
Part 5
305
306
Chapter
15
Chapter15
307
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
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));
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.
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.
Syntax
setFileType(short eFileType)
310
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
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));
311
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
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
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));
313
If a password is entered, a second Protect Sheet dialog appears. 4 Re-type the password. 5 Choose OK.
314
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");
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));
Code Example
This code example copies both the objects and data from multiple files into a single workbook.
316
// 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.
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());
Syntax
public com.f1j.ss.ReadResults read(byte blob[], com.f1j.ss.ReadParams rp);
318
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());
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;
319
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
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){ }
321
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);
Code Example
jbook1.write("C:\\F1Java\\tabbed.txt", new com.f1j.ss.WriteParams(jbook1.eFileTabbedText));
322
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));
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:
height-twips
324
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;
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
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
<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"> </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>
329
</xsl:stylesheet>
330
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();
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
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(); }
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
// 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); } } }
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; } }
336
<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>
337
338
Chapter
16
Chapter16
Printing
Changing print settings Printing headers, footers, and titles Odds and Ends of Printing
339
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);
340
Code Example
jbook1.setPrintLandscape(true);
Code Example
String myPrintArea = jbook1.getPrintArea();
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
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");
342
Code Example
jbook1.deleteDefinedName("Print_Area");
Code Example
Jbook1.setPrintNoColor(true);
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);
343
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
Code Example
try { jbook1.setPrintScale(100, true, 100, 1); jbook1.filePrint(false); } catch (com.f1j.util.F1Exception err) { }
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.
345
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
Code Example
jbook1.setPrintColHeading(true); jbook1.setPrintRowHeading(true);
346
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.
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.
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.
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
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);
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);
Code Example
This code prints the first two rows and the first column on every page.
jbook1.setPrintTitles("A1:AVLH2, A1:A1073741824");
Code Example
For more information and a code example, see Using draw to print in Chapter 8, Formatting worksheets.Using draw to print.
350
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
351
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
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);
353
354
Chapter
17
Converting e.Spreadsheet data to HTML
Chapter 17
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.
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.
356
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.
357
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.
358
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.
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
For more information on any of these fields, see the JRun documentation.
360
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.
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
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.
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.
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.
364
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.
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.
366
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.
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 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
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.
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
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>
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.
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.
372
... </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.
373
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.
374
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.
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.
375
376
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
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
378
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
# 1
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
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
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
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
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
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
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.
characterdelimiter
columnpositions
columnnames
386
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.
jndi
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.
String strDatapointCoordinates
388
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.
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.
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
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.
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
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.
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
393
394
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).
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
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
String strGetRangeText3[][][]
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
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
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
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
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 . . . />
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.
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
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
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
InsertVersion
Inserts a text string indicating which version of the JSP Charting API is being used. Syntax
<f1:InsertVersion/>
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.
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
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
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
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
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.
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.
409
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
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.
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
411
property keys and their tags, later in this chapter.List of property keys and their tags.
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
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
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:/).
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.
414
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>
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
416
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.
417
f1taglib.image.disksize
f1taglib.image.maxthreads
418
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
419
420
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)
421
422
Chapter
18
Chapter 18
Troubleshooting
Troubleshooting worksheet functions that return #DIV/0! Troubleshooting very slow screen redraws
423
424
Code Example
jbook1.setIterationEnabled(true); jbook1.setIterationMax(500); jbook1.setIterationMaxChange(.001);
and cell A1 contains a text value (or any number other than 1), the IF statement will return false.
425
426
Chapter
19
Chapter 19
Introduction Using e.Spreadsheet on Unix with a graphics device Using e.Spreadsheet on Unix without X-Windows Using setColWidthAuto with no GUI
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.
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
428
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
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
429
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.
430
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.
431
432
Appendix
A
Chapter 19
Additional Information
e.Spreadsheet maximums and minimums Links to more information Converting legacy code from AWT to Swing e.Spreadsheet files
Appendix A
433
434
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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