Java Excel API TUTORALIAL

zhaozj2021-02-16  123

Java Excel API TUTORALIAL

Contents

Introduction

Reading a spreadsheet

Writing a spreadsheet

?????

Fundamentals

?????

Adding Format Information

?????

Formatting Numbers

?????

Formatting dates

Copying and modify a spreadsheet

Demo & Test Programs

FREQUENTLY Asked Questions

?????

Java.lang.OutofMemory Exception

?????

Compiable

?????

Uploading a spreadsheet

?????

Support for charts, macros and images

?????

Date Display

?????

Cell Formats Across Multiple Workbooks

?????

Cross Sheet Formulas

Introduction The information presented in this tutorial is intended as a brief overview as to how JExcelApi may be used to read and write data in Excel format. The tutorial is by no means exhaustive, and if something is not described here, it does not mean that it can not be done. The reader is encouraged to examine the API documentation and the sample code (particularly Write.java and ReadWrite.java) in order to gain a more complete understanding of the capabilities and limitations of the software.

Reading Spreadsheets JExcelApi can read Excel spreadsheet from a file stored on the local filesystem or from some input stream. The first step when reading a spreadsheet from a file or input stream is to create a Workbook. The code fragment below illustrates creating an a workbook from A File on The Local FileSystem.

Import java.io.file; import java.util.date; import jxl. *; ... workbook workbook = workbook.getWorkbook (New file ("myfile.xls"));

(NOTE: WHEN CREANG A SPREADSHEET from a servletinputstream you must remove the http header information before what creating the workbook object.)

Once you have accessed the workbook, you can use this to access the individual sheets These are zero indexed -. The first sheet being 0, the second sheet being 1, and so on (You can also use the API to retrieve a sheet by. Name). SHEET Sheet = Workbook.getsheet (0);

Once you have a sheet, you can then start accessing the cells. You can retrieve the cell's contents as a string by using the convenience method getContents (). In the example code below, A1 is a text cell, B2 is numerical value and C2 IS a date. The Contents of these Cells May Be Accessed As Follows

Cell A1 = Sheet.getcell (0); Cell B2 = Sheet.getcell (1, 1); Cell C2 = Sheet.getcell (2, 1); string stringa1 = a1.getContents (); string stringb2 = b2. GetContents (); string stringc2 = c2.getContents (); // do stuff with the strings etc ...

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

However if it is required to access the cell's contents as the exact type ie. As a numerical value or as a date, then the retrieved Cell must be cast to the correct type and the appropriate methods called. The section of code below illustrates how JExcelApi may be used to retrieve a genuine java double and java.util.Date object from an Excel spreadsheet. For completeness the label is also cast to it's correct type, although in practice this makes no difference. The example also illustrates how to verify that cell IS of the expected type - this can be useful when Validating That The Spreadsheet Has Cells in The Correct Place.

String stringa1 = NULL; Double Numberb2 = 0; Date Datec2 = NULL; Cell A1 = Sheet.getcell (0); Cell B2 = Sheet.getcell (1, 1); Cell C2 = Sheet.Getcell (2, 1) ; if (a1.gettype () == celltype.label) {?? labelcell lc = (labelcell) A1; ?? stringa1 = lc.getstring ();} if (b2.gettype () == cellType.Number) { ?? Numbercell NC = (Numbercell) B2; ?? Numberb2 = nc.getValue ();} if (c2.gettype () == cellType.date) {?? Datecell DC = (Datecell) C2; ?? Datec2 = DC .getDate ();.} // Do stuff with dates and doubles ... When you have finished processing all the cells, use the close () method This frees up any allocated memory used when reading spreadsheets and is particularly important when reading large Spreadsheets.

// Finished - Close The Workbook and Free Up Memory Workbook.Close ();

Writing spreadsheets

Fundamentals This section describes how to write out simple spreadsheet data without any formatting information, such as fonts or decimal places. Similarly to reading a spreadsheet, the first step is to create a writable workbook using the factory method on the Workbook class.

Import java.io.date; import jxl. *; import jxl.write. *; ... Writableworkbook workbook = workbook.createworkbook (New file ("output.xls");

This creates the workbook object. The generated file will be located in the current working directory and will be called "output.xls". The API can also be used to send the workbook directly to an output stream eg. From a web server to the User's Browser. if The Http Header IS Set Correctly, The This Will Launch Excel and Display The Generated Spreadsheet.

The next stage is to create sheets for the workbook. Again, this is a factory method, which takes the name of the sheet and the position it will occupy in the workbook. The code fragment below creates a sheet called "First Sheet" at the First position.writablesheet sheet = workbook.createsheet ("first sheet", 0);

Now all that remains is to add the cells into the worksheet. This is simply a matter of instantiating cell objects and adding them to the sheet. The following code fragment puts a label in cell A3, and the number 3.14159 in cell D5.

Label label = new label (0, 2, "a label record"); Sheet.Addcell (label); Number Number = New Number (3, 4, 3.1459); Sheet.Addcell (Number);

There are a couple of points to note here. Firstly, the cell's location in the sheet is specified as part of the constructor information. Once created, it is not possible to change a cell's location, although the cell's contents may be altered.

THETHER POINT TO Note Is That The Cell's Location IS Specified As (Column, Row). Both Are Zero Indexed Integer Values ​​- A1 Being Reperesented by (0), B1 by (1, 0), A2 by (0, 1 And So ON.

Once you have finished adding sheets and cells to the workbook, you call write () on the workbook, and then close the file. This final step generates the output file (output.xls in this case) which may be read by Excel. If You Call Close () WITHOUT CALLING WRITE () FIRST, A COMPLETESELY Empty File Will Be generated.

... // All Sheets and Cells Added. Now Write Out The Workbook Workbook.write (); Workbook.close ();

Adding Format Information The previous section illustrates the fundamentals of generating an Excel compatible spreadsheet using the JExcelApi. However, as it stands Excel will render the data in the default font, and will display the numbers to 3 decimal places. In order to supply formatting information to Excel, we must make use of the overloaded constructor, which takes an additional object containing the cell's formatting information (both the font and the style). The code fragment below illustrates creating a label cell for an arial 10 point font.// Create a cell format for Arial 10 point font WritableFont arial10font = new WritableFont (WritableFont.ARIAL, 10); WritableCellFormat arial10format = new WritableCellFormat (arial10font); // Create the label, specifying content and format label label2 = new label (1,0, "Arial 10 Point Label", Arial10Format; Sheet.Addcell (label2);

Cell Formats Objects Are Shared, So Many Cells May Use The Same Format Object, EG.

Label Label3 = New Label (2, 0, "Another Arial 10 Point Label", Arial10Format; Sheet.Addcell (label3);

THIS CREATES ANOTHER LABEL, WITH THE SAME FORMAT, IN CELL C1.

Because cell formats are shared, it is not possible to change the contents of a cell format object. (If this were permitted, then changing the contents of the object could have unforeseen repurcussions on the look of the rest of the workbook). In order To change the way a particular cell is displayed, The API Does allow you to assign a new format to an an indeividul cell.

The constructors for the WritableFont Object Have Many Overloads. By Way of Example, The Creates A Label in 16 Point Times, Bold Italic and Assigns It to position d1.

// Create a cell format for Times 16, bold and italic WritableFont times16font = new WritableFont (WritableFont.TIMES, 16, WritableFont.BOLD, true); WritableCellFormat times16format = new WritableCellFormat (times16font); // Create the label, specifying content and format label label4 = new label (3,0, "Times 16 bold italic label", times16format); sheet.addCell (label4); Formatting Numbers Number formatting information may be passed to the cell format object by a similar mechanism to that described for FONTS. A Variety of Predefined Number Formats Are Defined Static, these May BE USED TO FORMAT NUMERICAL VALUES AS FOLLOWS:

WritableCellFormat integerFormat = new WritableCellFormat (NumberFormats.INTEGER); Number number2 = new Number (0, 4, 3.141519, integerFormat); sheet.addCell (number2); WritableCellFormat floatFormat = new WritableCellFormat (NumberFormats.FLOAT); Number number3 = new Number ( 1, 4, 3.141519, floatformat; Sheet.Addcell (Number3);

The above code inserts the value 3.14159 into cells A5 and B5, using the preset integer and floating points format respectively. When Excel renders these cells, A5 will display as "3" and B5 will display as "3.14", even though both cells contain The Same Floating Point Value.

It's possible for a user to define their own number formats, by passing in a number format string. The string passed in should be in the same format as that used by the java.text.DecimalFormat class. To format a number to display up to FIVE DECIMAL Places in Cell C5, The Following Code Fragment May BE USED:

NumberFormat fivedps = new NumberFormat ( "# #####."); WritableCellFormat fivedpsFormat = new WritableCellFormat (fivedps); Number number4 = new Number (2, 4, 3.141519, fivedpsFormat); sheet.addCell (number4); It is , Of Course, Also Possible to Specify Font Information As Well Eg. To Display The Same Value In The 16 Point Times Bold Font Defined Earlier We Can Write

WritablecellFormat FivedpsFontFormat = new WritablecellFormat (Times16Font, Fivedps); Number Number5 = New Number (3, 4, 3.141519, FivedpsFontFormat); Sheet.Addcell (Number5);

Formatting Dates Dates are handled similarly to numbers, taking in a format compatible with that used by the java.text.SimpleDateFormat class. In addition, several predefined date formats are specified in the jxl.write.DateFormat class. As a brief example, the Below Code Fragment Illustrates Placing The Current Date And Time IN Cell A7 Using A Custom Format:

// Get the current date and time from the Calendar object Date now = Calendar.getInstance () getTime (); DateFormat customDateFormat = new DateFormat. ( "Dd MMM yyyy hh: mm: ss"); WritableCellFormat dateFormat = new WritableCellFormat (customDateFormat ); DateTime Datecell = New DateTime (0, 6, now, dateformat); Sheet.Addcell (Datecell);

As with numbers, font information may be used to display the date text by using the overloaded constructors on WritablecellFormat.

For a more extensive example of writing spreadsheets, the demonstration program Write.java should be studied. In addition to the functionality described above, this program tests out a variety of cell, formatting and font options, as well as displaying cells with different background and Foreground colours, Shading and Boundaries.

Copying and Modifying Spreadsheets This section describes the scenario where a spreadsheet is read in, it's contents altered in some way and the modified spreadsheet written out The first stage is to read in the spreadsheet in the normal way.:

Import java.io.file; import java.util.date; import jxl. *; import jxl.write. *; ... workbook workbook = workbook.getWorkbook (New file ("myfile.xls"));

This Creates a Readable Spreadsheet. To Obtain A Writable Version of this Spreadsheet, A Copy Must Be Made, As Follows:

Writableworkbook copy = workbook.createworkbook (new file ("output.xls"), Workbook;

The API functions this way is for reasons of read efficiency (since this is the primary use of the API). In order to improve performance, data which relates to output information (eg. All the formatting information such as fonts) is not interpreted when the spreadsheet is read, since this is superfluous when interrogating the raw data values. However, if we need to modify this spreadsheet a handle to the various write interfaces is needed, which can be obtained using the copy method above. This copies the information that has already been read in as well as performing the additional processing to interpret the fields that are necessary to for writing spreadsheets. The disadvantage of this read-optimized strategy is that we have two spreadsheets held in memory rather than just one, thus doubling the memory ......................

Once we have a writable interface to the workbook, we may retrieve and modify cells. The following code fragment illustrates how to modify the contents of a label cell located in cell B3 in sheet 2 of the workbook.WritableSheet sheet2 = copy.getSheet (1 Writablecell Cell = Sheet2.Getwritablecell (1, 2); if (Cell.gettype () == CellType.Label) {?? Label L = (Label) Cell; ?? L.SetString ("Modified Cell"); }

There is no need to call the add () method on the sheet, since the cell is already present on the sheet. The contents of numerical and date cells may be modified in a similar way, by using the setValue () and setDate () Methods respectively.

Although cell formats are immutable, the contents of a cell may be displayed differently by assigning a different format object to the cell. The following code fragment illustrates changing the format of numerical cell (in position C5) so that the contents will be displayed to five DECIMAL Places.

WritableSheet sheet2 = copy.getSheet (1); WritableCell cell = sheet2.getWritableCell (2, 4); NumberFormat fivedps = new NumberFormat ( "# #####."); WritableCellFormat cellFormat = new WritableCellFormat (fivedps); cell. SetFormat (CellFormat);

Since the copy of the workbook, new cells may be added to the sheet, thus:

Label Label = New Label (0, 2, "New Label Record"); Sheet2.Addcell (Label); Number Number = New Number (3, 4, 3.1459); Sheet2.Addcell (Number);

AS Before, Once The Modifications Are Complete, The Workbook Must Be Written Out and Closed.

... // All Cells Modified / Added. Now Write Out The Workbook Copy.write (); Copy.close ();

The demo program contained in the source file ReadWrite.java may be studied as a more exhaustive example of how spreadsheets may be modified This demo program copies the spreadsheet passed in on the command line;. If the spreadsheet to be copied is the example spreadsheet, jxlrwtest.xls, located in the current directory, then certain modifications are carried out. DO nOT MODIFY THE EXAMPLE SPREADSHEET, otherwise the demo program will not work.Demonstration and Test Programs JExcelApi comes with a raft of demonstration and test programs contained in the package JXL.Demo. Thase May Be Accessed from The Command Line As Follows

Java -jar jxl.jar -csv spreadsheet.xls

Reads Spreadsheet.xls and Writes Out The Corresponding CSV Data To The Standard Output. The -csv Option Is The Default and May Omitted

Java -jar jxl.jar -Xml spreadsheet.xls

.

Java -jar jxl.jar -xml -format spreadsheet.xls

AS ABOVE, But includees formatting information (font, number formats etc) in The generated XML

Java -jar jxl.jar-formulas spreadsheet.xls

Reads Spreadsheet.xls and Displays All The Formulas Contained in That Sheet.

Java -jar jxl.jar -write test.xls

Generates a Sample Test Spreadsheet Called Test.xls

Java -jar jxl.jar -rw in.xls Out.xls

Reads in.xls, copies it and generates a file called out.xls. If the spreadsheet passed in is a special sample spreadsheet called jxlrwtest.xls, then this demo will modify specific cells in the copy, out.xls.

FREQUENTLY Asked Questions

java.lang.OutOfMemory Exception By default a JVM places an upper limit on the amount of memory available to the current process in order to prevent runaway processes gobbling system resources and making the machine grind to a halt. When reading or writing large spreadsheets, the JVM may require more memory than has been allocated to the JVM by default -. this normally manifests itself as a java.lang.OutOfMemory exception For command line processes, you can allocate more memory to the JVM using the -Xms and -Xmx options eg TO Allocate AN Initial Heap Allocation of 10 MB, with 100 MB as The Upper Bound You Can Usejava -xms10m -xmx100m -classpath jxl.jar spreadsheet.xls

.

Compiable

The distribution of JExcelApi comes with a build.xml file. This may be used by the build tool, ant, in order to build the software. If ant is not already installed on your machine, it may obtained here. To build API using ant SIMPLY CHANGE to the Subdirectory Called Build, From The Command Line, Type

Ant

.

Totally of targets. To Totally Rebuild The WHOLE Application, Including The Javadoc Documentation, The Obtain A Command Line Prompt With Build Directory and Type

Ant JxLall

As an alternative to using ant, JExcelApi may be built using the standard java tools From the command line in the build subdirectory issue the following sequence of commands (modifying file separators and classpath separators as required for the target operating system).:

Javac -d out -classpath out: ../ src ../src/jxl/demo/*.java jar cmf jxl.mf ../jxl.jar -c outss jxluploading spreadsheets via the Browser Below Is some Indicative Code Which May Be Used for Uploading Spreadsheets from aclient browser to servlet. in The Html Page Which is displayed to the user requesting The Upload, Declare A Form of Multipart Form Data:

The servlet which process the.

Accessing the Input Stream Directly Means That The Http Information IS PRISTING THISTANT INFORMATION BEFORE Passing The Input Stream Directly To The API, thus:

protected void doPost (HttpServletRequest request, HttpServletResponse response) ?? throws IOException, ServletException {?? try ?? {???? ServletInputStream is = request.getInputStream (); ???? byte [] junk = new byte [1024] ; ???? int BytesRead = 0; ???? // The first four Lines Are Request Junk ???? BytesRead = is.readline (Junk, 0, junk.length); ???? bytesread = IS. Readline (Junk, 0, Junk.Length); ???? bytesread = is.readline (junk, 0, junk.length); ???? BytesRead = Is.Readline (junk, 0, junk.length);? ??? Workbook workbook = workbook.getworkbook (is); ???? // do stuff with the workbook ???? ... ??} ?? Catch (jxlexception e) ?? {???? .. . ??}}

Support for charts, macros and images JExcelApi has limited support for charts: when copying a spreadsheet containing a chart, the chart is written out to the generated spreadsheet (as long as the sheet containing the chart contains other data as well as the chart). All macro and information is ignored. Consequently when copying and writing out the macros that were in the original will not be present in the generated version. All image information is preserved when copying spreadsheets. When adding an image to a spreadsheet only images in PNG format Aresuted

Date display When displaying dates, the java.util package automatically adjusts for the local timezone. This can cause problems when displaying dates within an application, as the dates look as if they are exactly one day previous to that which is stored in the Excel spreadsheet , although this is not in fact the case. Excel stores dates as a numerical value, and the conversion process for transforming this into a java.util.Date consists of converting the Excel number into a UTC value and then using the UTC number to create the java Date. Say the number in Excel represents 20 August 2003, then the UTC equivalent of this number is used to create a java.util.Date object. The problem occurs if you are operating in a timezone other than GMT. As soon as you try and perform any user IO on that java Date object the JVM will perform timezone adjustment calculations If you are located in EST zone (which is GMT - 5 hours) (eg System.out.print (date).). java will subtract 5 Hours from the date - So the date Object instead of becomes 19:00 19/08/2003. Because Java Recognizes You ONLY WANT A DATE AND NOTED A DATE TIME, IT TRUNCATES The Hours / Minutes / Seconds and Presents 19 / 08/2003 - SO IT APPEARS That The Day Is One Day Less Than Was Stored in Excel, WHEREAS IT IS Really Only A Few Hours (The Timezone Offset) Less. Needless to Say, This Is A Very Annoying Feature. The Easiest Way To Work Around this (and the method buy "by the getContents () Method of a jxl.datecell) is to force the timezone of the date format as Follows:

TimeZone gmtZone = TimeZone.getTimeZone ( "GMT"); SimpleDateFormat format = new SimpleDateFormat ( "dd MMM yyyy"); format.setTimeZone (gmtZone); DateCell dateCell = .... String dateString = format.format (dateCell.getDate ( ));. Cell Formats Across Multiple Workbooks Sometimes a single process may generate multiple workbooks When doing this is it tempting to create the various cell formats once (eg as member data or as static constants) and apply them to cells in both workbooks.. This works fine for the first workbook, but for subsequent workbooks this can cause unexpected cell formatting. The reason for this is that when a format is first added to a workbook, JExcelApi assigns an internal cross-reference number to that cell, and all other cells which share this format simply store the cross reference number. However, when you add the same cell format to a different workbook, JExcelApi recognizes that the format has been added to a workbook, and simply refers to the format by the index number, ra ther than by initializing it properly. When Excel then tries to read this workbook, it sees an index number, but is unable to read the cell format (or reads a different one) as the cell can be formatted in an unpredictable manner. The long and the short of it is that if it is necessary to re-use formats across multiple workbooks, then the WritableCellFormat objects must be re-created and initialised along with the each Workbook instance, and NOT re-used from a previous workbook.

Cross Sheet Formulas JExcelApi supports formulas across sheets. However, please make sure all the sheets have been added to the workbook (even if they are blank) before attempting to create cross sheet formulas. This is because if you create a cross sheet formula referencing a sheet and then subsequently and or remove sheets from the workbook, the sheet reference in the formula when it was parsed will not necessarily reference the correct sheet, and could even cause Excel to crashBack to JExcelApi home

转载请注明原文地址:https://www.9cbs.com/read-8689.html

New Post(0)