[Java Diary] Comprehensive Mining Java Excel API Usage Call Moon Palace Published on 2004-12-27 14:26:35
Friends using the Windows operating system must not be unfamiliar with Excel, but to use Java language to manipulate the Excel file is not an easy task. Today, the Web is increasingly popular, the demand for the Excel file is increasing through the web, and the current more popular operation is to create a CSV (Comma Separated Values) file in the JSP or Servlet, and will file this file with MIME, TEXT / CSV type returns to the browser, then calls Excel and displays the CSV file. This is just to say that you can access the Excel file, but you can't really manipulate the Excel file. This article will give you a surprise, introduce you to an open source project, Java Excel API, use it, you can easily manipulate the Excel file. Java Excel API Introduction Java Excel is an open source project, through its Java developers, you can read the contents of the Excel file, create a new Excel file, update the existing Excel file. Using this API non-Windows operating system can also process the Excel data table by pure Java applications. Because it is written in Java, we can call the API to implement access to the Excel data table in a web application. The currently released stability is V2.0, providing the following functions: read data from the Formats such as Excel 95, 97, 2000; read the Excel formula (the formula after reading Excel 97); generate an Excel data table ( Format is Excel 97); support font, numbers, date formatting; support cell shadow operation, and color operation; modify the existing data table; now do not support the following features, but will soon provide: Read chart information; readable, but cannot generate formulas, any type of formula last calculated value can be read; Application Example 1, read data sheet from the Excel file Java Excel API can either from a local file system (. XLS), you can also read the Excel data table from the input stream. The first step in reading the Excel data is to create Workbook (Terminology: Working). The following code snippet is explained how to operate: (full code see Excelreading.java)
Import java.io. *; import jxl. *; ... ... ... ... ... ... Try {// Build a Workbook object, read-only Workbook object // Create Workbook directly from the local file to create WorkbookInputStream IS = New FileInputStream (Sourcefile) JXL.Workbook RWB = Workbook.getWorkbook (IS);} catch (Exception E) {E.PrintStackTrace ();} Once you have created Workbook, we can access Excel Sheet by it. Refer to the following code segment:
// Get the first Sheet table sheet = rwb.getsheet (0); we may access it through the name of Sheet, or you can access it through the subscript. If you are accessible by the subscript, you should pay attention to the starting mark from 0, just like an array. Once you get the Sheet, we can access Excel Cell (Terms: Cell). Refer to the following code snippet: // Get the first line, the value of the first column Cell C00 = gtcell (0); string strc00 = c00.getContents (); // Get the first line, second column Value Cell C10 = rs.getcell (1, 0); string strc10 = c10.getContents (); // Gets the second line, the second column value Cell C11 = rs.getcell (1, 1); string strC11 = C11 .getContents (); System.out.println ("Cell (0, 0)" "value:" strc00 "; type:" c00.gettype (); system.out.println ("Cell (1 0) " " value: " strc10 "; type: " c10.gettype ()); system.out.println (" Cell (1, 1) " " value: " strc11 "; type : " C11.Gettype ()); if it is only the value of Cell, we can easily return any type of CELL value as a string by getContents () method. Cell (0, 0) in the sample code is text type, Cell (1, 0) is a digital type, Cell (1, 1) is a date type, through getContents (), three types of return values are characters. If you need to know the exact type of Cell content, the API also provides a range of methods. Refer to the following code segment:
String strc00 = null; double strc10 = 0.00; Date strc11 = NULL; Cell C00 = rs.getcell (0, 0); Cell C10 = rs.getcell (1, 0); Cell C11 = rs.getcell (1, 1) ; if (c00.gettype () == celltype.label) {Labelcell Labelc00 = (labelcell) c00; strc00 = labelc00.getstring ();} if (c10.gettype () == cellType.Number) {nmberCell Numc10 = ( Numbercell) C10; strc10 = Numc10.getValue ();} if (c11.gettype () == cellType.date) {datecell datec11 = (Datecell) C11; strc11 = datec11.getdate ();} system.out.println "Cell (0, 0)" "value:" strc00 "; type:" c00.gettype ()); system.out.println ("Cell (1, 0)" "value:" STRC10 "; type:" c10.gettype ()); System.out.Println ("Cell (1, 1)" "Value:" STRC11 "; TYPE:" C11.Gettype ()); After obtaining the Cell object, the type of the cell can be obtained by getType () method, and then match the basic type provided by the API, forcibly converting into a corresponding type, and finally call the corresponding value method getxxx (), you can get it. Type value. The API provides the following basic types, corresponds to the data format of Excel, as shown in the following figure: For each type of specific meaning, see Java Excel API Document. When you complete the processing of Excel spreadsheet data, you must use the close () method to close the previously created object to release the memory space occupied by the read data table, which is especially important when reading a large amount of data. . Refer to the following code segment: // When the operation is complete, turn off the object, release the occupied memory space RWB.Close (); Java Excel API provides many ways to access the Excel data table, here I only briefly introduce several common methods For other methods, please refer to Java Excel API Document in the appendix. Methods offered by Workbook class 1. INT getNumberOfsheets () Gets the number of worksheets (Sheets) in Workbook, examples:
JXL.Workbook RWB = jxl.workbook.getWorkbook (new file (sourcefile)); int Sheets = rwb.getnumberofsheets (); 2. Sheet [] getSheets () Returns the Workbook Worksheet (Sheet) Object Array, Example:
JXL.Workbook RWB = jxl.workbook.getWorkbook (new file (sourcefile)); Sheet [] Sheets = rwb.getsheets (); 3. String getVersion () Returns the version number of the API that is in use, it seems that there is nothing too big effect.
JXL.Workbook RWB = jxl.workbook.getWorkbook (new file (sourcefile)); String Apiversion = rwb.getversion (); method provided by Sheet Interface 1) String getName () Gets the name of the Sheet, example:
JXL.Workbook RWB = jxl.workbook.getworkbook (new file (sourcefile)); jxl.sheet = rwb.getsheet (0); string sheetname = rs.getName (); 2) int getColumns () Get the Sheet Table The total number of columns included, examples:
JXL.Workbook RWB = jxl.workbook.getworkbook (new file (sourcefile)); jxl.sheet = rwb.getsheet (0); int gcolumns = rs.getColumns (); 3) Cell [] getColumn (int column) Get All cells of a column returns a cell object array, example:
JXL.Workbook RWB = jxl.workbook.getWorkbook (new file (sourcefile)); jxl.sheet = rwb.getsheet (0); cell [] cell = rs.getColumn (0); 4) Int getRows () Get Sheet The total number of lines included in the table, examples:
JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile)); jxl.sheet = rwb.getsheet (0); int gROWS = rs.getrows (); 5) Cell [] getRow (int ROW) Get All cells of a certain row, returning the cell object array, an example:
JXL.Workbook RWB = jxl.workbook.getWorkbook (new file (sourcefile)); jxl.sheet = rwb.getsheet (0); cell [] cell = rs.getrow (0); 6) Cell getcell (int Column, int ROW) Gets object references for specifying cells, you need to pay attention to its two parameters, the first is the number of columns, the second is the number of lines, which is different from the usual row, and the column combination is somewhat different.
JXL.Workbook RWB = jxl.workbook.getworkbook (new file (source (sourcefile)); jxl.sheet = rwb.getsheet (0); cell cell = rs.getcell (0, 0); 2, generate new Excel workbook The following code is mainly to introduce you how to generate a simple Excel worksheet, where the content of the cell is no modified (e.g., font, color, etc.), and all the content is written as a string. (Full code See Excelwriting.java) Similar to reading Excel worksheets, first create a Workbook object using the factory method of the Workbook class, hereby pay attention, can only be provided by the API Method to create Workbook, not to use WritableWorkbook constructor because the constructor of class WritableWorkbook is protected by protected type. The sample code snippet is as follows: import java.io. *; Import jxl. *; Import jxl.write. *; ... ... ... ... ... ... ... ... Try {// Build a Workbook object, read-only Workbook object // Method 1: Create a writable Excel workbook jxl.write.WritableWorkbook wwb = Workbook.createWorkbook (new File (targetfile)); // Method 2: WritableWorkbook written directly to the output stream / * OutputStream os = new FileOutputStream (targetfile); jxl.write.WritableWorkbook WWB = Workbook.createworkbook (OS); * /} catch (Exception E) {E.PrintStackTrace ();} API provides two ways to process writable output streams, one is to generate local files, if file If the name does not have a full path, the default file will be positioned in the current directory. If the file name comes with a full path, the generated Excel file is positioned in the corresponding directory; the other is to write the Excel object directly to Output stream, for example: users access the web server through the browser, if the HTTP header is set correctly, the browser automatically calls the client's Excel application to display dynamically generated Excel spreadsheets. The next step is to create a worksheet, the method of creating a worksheet is almost the same as the method of creating a work, and the corresponding object is also obtained through the factory mode method. This method requires two parameters, one is the name of the worksheet, the other is The worksheet is in the position of the work, refer to the following code snippet:
// Create an Excel worksheet jxl.write.writablesheet ws = wwb.createsheet ("Test Sheet 1", 0); "This pot is also supported, the material is also ready, you can start the pot!" It is only the EXCEL basic data type provided by the API, and it is possible to add them to the worksheet. Refer to the following code segment: // 1. Add label object jxl.write.label labelc = new JXL.WRITE .Label (0, 0, "this is a label cell"); ws.addcell (labelc); // Add a word formatting object jxl.write.writablefont wf = new jxl.write.writableFont (WritableFont.Times , 18, WritableFont.Bold, True; JXL.WRITE.WRITABECECELLFORMAT WCFF = New JXL.WRITE.WRITABECELLFORMAT (WF); jxl.write.label labelcf = new jxl.write.Label (1, 0, "this is a label Cell ", WCFF); ws.addcell (labelcf); // Add object with font color formatting jxl.write.writablefont wfc = new jxl.write.writablefont (Writablefont.arial, 10, Writablefont.No_Bold, False, underlinestyle .No_underline, jxl.format.colour.red; jxl.write.writablecellformat wcffc = new jxl.write.writablecellFormat (WFC); jxl.write.label labelcfc = new jxl.write.label (1, 0, "this is A label cell ", WCFFC); ws.addcell (labelcf); // 2. Add Number object jxl.write.Number labeln = new jxl.write.Number (0, 1, 3.1415 926); ws.addcell (labeln); // Add Number object with formatting, jxl.write.NumberFormat nf = new jxl.write.Numberformat ("#. ##"); jxl.write.writablecellformat wcfn = new jxl .write.writablecellformat (nf); jxl.write.number labelnf = new jxl.write.Number (1, 1, 3.1415926, ws.addcell (labelnf); // 3. Add Boolean object jxl.write.Boolean Labelb = new jxl.write.boolean (0, 2, false); ws.addcell (labelb); // 4. Add a DateTime object jxl.write.datetime labeldt = new jxl.write.datetime (0, 3, New Java .util.date ()); ws.addcell (labeldt); // Add a DateFormat object with formatting jxl.write.dateFormat DF = New jxl.write.dateFormat ("
DD MM YYYY HH: MM: SS "); jxl.write.writablecellformat wcfdf = new jxl.write.writablecellFormat (DF); jxl.write.datetime labeldtf = new jxl.write.datetime (1, 3, new java.util .Date (), wcfdf); ws.addcell (labeldtf); there are two points to cause everyone to pay attention. First point, when constructing cells, the location of cells in the worksheet is already determined. Once After the creation, the location of the cell is unable to change, although the content of the cell can be changed. The second point, the positioning of the cell is the rulern, row, and the subscript is from 0 Start, for example, A1 is stored in (0, 0), B1 is stored in (1, 0). Finally, don't forget to close the open Excel workmail object, to release the occupied memory, see the following code segment: // Write an Exel worksheet Wwb.write (); // Close Excel workmail object wwb.close (); this may have little difference with the operation of reading the Excel file, before closing the Excel object, you must call WRITE first The method, because the previous operation is stored in the cache, so the contents of the operation are saved in the file through this method. If you turn off the Excel object first, then you can only get an empty work. 3 , Copy, update Excel work thin Next briefly introduces how to update an existing work, mainly the following two steps, the first step is to construct read-only Excel work, the second step is to use the EXCEL work that has been created Thin creation of newly writable Excel works, refer to the following code snippet: (complete code see ExcelModifying.java)