Jxl (Java Excel API) is an open-source framework for dynamically reading and writing Excel files. It can be used to dynamically read and write Excel files on any operating system that supports Java. Jxl homepage: http://www.andykhan.com/jexcelapi/. you can download the latest version of jxl.
You can run the following commands respectively:
Java-jar jxl. jar-XML test.xls
Java-jar jxl. jar-CVS test.xls
Use xmland cvsformat to define test.xls. This is because the author of jxl implements a jxl. Demo. demo class for demonstration.
Of course, we use jxl to dynamically read and write Excel files. Now let's take a look at the support of jxl in reading and writing excel.
Let's take a look at the above objects in the Excel file.
1 file object 2 workbook object 3 cell object.
Corresponding workbook, sheet, and cell are available in jxl. With these three objects, we can read Excel files.
Let's first think about the reading process. No matter what kind of Excel operating framework, we must go through
1. Select an Excel file, 2. Select a workbook, 3. Select cell, and 4. read information.
Now let's take a look at how these four steps are embodied in jxl:
// Use the static workbook method getworkbook to select an Excel file
Workbook workbook = Workbook. getworkbook (new file ("myfile.xls "));
// Use the getsheet method of the workbook to select the first Workbook (starting from 0)
Sheet sheet = Workbook. getsheet (0 );
// Use the getcell method of the sheet method to select a cell with the position of C2 (both parameters start from 0)
Cell C2 = sheet. getcell (2, 1 );
// Use the getcontents method of cell to read the information in cells as characters
String stringc2 = c2.getcontents ();
We can see that the four steps are just described.
We all know that excel cells are formatted and how to obtain the information.
Cell provides a GetType method to return the type information of cells, and jxl provides a celltype class to preset the type information in Excel, in addition, jxl provides some cell subclass used to represent various types of cells, such as labelcell, numbercell, and datecell, which respectively represent cells of the character, value, and date types. So we can write:
If (c2.gettype () = celltype. Number)
{
Numbercell NC = (numbercell) C2;
Numberb2 = nC. getvalue ();
}
Do not forget to close the workbook to release resources:
Workbook. Close ();
Now let's sum up: three objects, four steps. Pay attention to the format. You can easily read data from an Excel file.