jxl的API

Friends who use the Windows operating system must not be unfamiliar with Excel (spreadsheet), but it is not an easy task to use the Java language to manipulate Excel files. Today, with the increasing popularity of Web applications, the demand for operating Excel files through the Web is becoming stronger and stronger. Currently, a more popular operation is to create a CSV (comma separated values) file in JSP or Servlet, and use MIME, text The /csv type is returned to the browser, which then calls Excel and displays the CSV file. This just means that you can access Excel files, but you can't really manipulate Excel files. This article will give you a surprise and introduce you to an open source project - Java Excel API , with which you can easily manipulate Excel files. Introduction to


JAVA EXCEL API
Java Excel is an open source project through which Java developers can read the contents of Excel files, create new Excel files, and update existing Excel files. Using this API , non-Windows operating systems can also process Excel data tables through pure Java applications. Because it is written in Java, we can call the API through JSP and Servlet to access the Excel data table in the Web application.

The stable version released now is V2.0, which provides the following functions:

· Read data from files in Excel 95, 97, 2000 and other formats;

· Read Excel formulas (can read formulas after Excel 97);

· Generate Excel Data table (in Excel 97 format);

Support font, number, date formatting;

· Supports cell shading and color manipulation;

· Modifying existing data tables;

· The following functions are not currently supported, but will be available soon:

· Can't read chart information;

can read, but can't generate formulas , the last calculated value of any type of formula can be read;


application example Read data table
from Excel file The

Java Excel API can read Excel data table from a file (.xls) in the local file system or from the input stream . The first step in reading an Excel data sheet is to create a Workbook (term: workbook). The following code snippet illustrates how this should be done: (see ExcelReading.java for the full code)

import java.io.*;
import jxl .*;
… … … …
try
{
//Build Workbook object, read-only Workbook object
//Create Workbook directly from local file
//Create Workbook from input stream
    InputStream is = new FileInputStream(sourcefile);
    jxl .Workbook rwb = Workbook.getWorkbook(is );
}
catch (Exception e)
{
e.printStackTrace();
}


Once the Workbook is created, we can use it to access the Excel Sheet (term: worksheet). Refer to the following code snippet:

//Get the first Sheet Sheet
Sheet rs = rwb.getSheet(0);


We may access it either by the name of the Sheet or by subscripting it. If you access it by subscript, one thing to note is that the subscript starts at 0, just like an array.

Once we have the Sheet, we can use it to access the Excel Cell (term: cell). Refer to the following code snippet:

//Get the value of the first row, the first column
Cell c00 = rs.getCell(0, 0);
String strc00 = c00.getContents();
//Get the first row, the second column Value
Cell c10 = rs.getCell(1, 0);
String strc10 = c10.getContents();
//Get the value of the second row and second column
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 we just get the value of Cell, we can easily pass the getContents() method, which can treat any type of Cell value as a character String is returned. In the sample code, Cell(0, 0) is a text type, Cell(1, 0) is a number type, and Cell(1,1) is a date type. Through getContents(), the return values ​​of the three types are all character types. The API also provides a series of methods

if you need to know the exact type of Cell content . Refer to the following code snippet: 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;






























The following basic types are provided, corresponding to the data format of Excel, as shown in the following figure:



For the specific meaning of each type, please refer to the Java Excel API Document.

When you have finished processing the Excel spreadsheet data, be sure to use the close() method to close the previously created object to release the memory space occupied in the process of reading the data table, which is particularly important when reading a large amount of data . Refer to the following code snippet:

//When the operation is completed, close the object and release the occupied memory space
rwb.close(); The


Java Excel API provides many methods for accessing Excel data tables, here I will only briefly introduce a few commonly used methods , for other methods, please refer to the Java Excel API Document in the appendix.

· Methods provided by the Workbook class

1. int getNumberOfSheets()

to get the number of sheets in the workbook (Workbook), example:

jxl .Workbook rwb = jxl .Workbook.getWorkbook(new File(sourcefile));
int sheets = rwb.getNumberOfSheets();


2. Sheet[] getSheets()

returns an array of Sheet objects in the Workbook, for example:

jxl .Workbook rwb =jxl .Workbook.getWorkbook(new File(sourcefile));
Sheet[] sheets = rwb.getSheets();


3. String getVersion()

returns the version number of the API being used , which doesn't seem to have much effect.

jxl .Workbook rwb = jxl .Workbook.getWorkbook(new File(sourcefile));
String apiVersion = rwb.getVersion();


Methods provided by the Sheet interface

1. String getName()

to get the name of the Sheet, for example:

jxl .Workbook rwb = jxl .Workbook.getWorkbook(new File(sourcefile));
jxl .Sheet rs = rwb.getSheet(0);
String sheetName = rs.getName();


2. int getColumns()

Get the total columns contained in the Sheet table Number, example:

jxl .Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile));
jxl .Sheet rs = rwb.getSheet(0);
int rsColumns = rs.getColumns();


3. Cell[] getColumn(int column)

gets all cells in a column , which returns an array of cell objects, for example:

jxl .Workbook rwb = jxl .Workbook.getWorkbook(new File(sourcefile));
jxl .Sheet rs = rwb.getSheet(0);
Cell[] cell = rs.getColumn( 0);


4. int getRows()

gets the total number of rows contained in the Sheet table, for example:

jxl .Workbook rwb = jxl .Workbook.getWorkbook(new File(sourcefile));
jxl .Sheet rs = rwb.getSheet(0) ;
int rsRows = rs.getRows();


5. Cell[] getRow(int row)

Gets all cells in a row and returns an array of cell objects, example:

jxl.Workbook rwb = jxl .Workbook.getWorkbook(new File(sourcefile));
jxl .Sheet rs = rwb.getSheet(0);
Cell[] cell = rs.getRow(0);


6. Cell getCell(int column, int row)

to get the object reference of the specified cell, it should be noted that its two parameters, the first is the number of columns, the second is the number of rows, which is somewhat different from the usual combination of rows and columns.

jxl .Workbook rwb = jxl .Workbook.getWorkbook(new File(sourcefile));
jxl .Sheet rs = rwb.getSheet(0);
Cell cell = rs.getCell(0, 0);


generate a new Excel workbook

below The code is mainly to show you how to generate a simple Excel worksheet, where the content of the cell is without any decoration (such as: font, color, etc.), and all the content is written as a string. (See ExcelWriting.java for the complete code.)

Similar to reading an Excel worksheet, first use the factory method of the Workbook class to create a writable Workbook object. It should be noted here that only through the APIProvides a factory method to create a Workbook, instead of using the WritableWorkbook constructor, because the class WritableWorkbook constructor is a protected type. The sample code snippet is as follows:

import java.io.*;
import jxl .*;
import jxl .write.*;
… … … …
try
{
//Build Workbook object, read-only Workbook object
//Method 1: Create writable Excel workbook
jxl .write.WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile));
//Method 2: Write WritableWorkbook directly to the output stream
/*
    OutputStream os = new FileOutputStream(targetfile);
    jxl .write.WritableWorkbook wwb = Workbook.createWorkbook(os);
*/
}
catch (Exception e)
{
e.printStackTrace();
}


APIProvides two ways to process the writable output stream. One is to directly generate a local file. If the file name does not have a full path, the default file will be located in the current directory. If the file name has a full path, Then the generated Excel file will be located in the corresponding directory; the other is to write the Excel object directly to the output stream, for example: the user accesses the web server through the browser, if the HTTP header is set correctly, the browser automatically calls the client An Excel application on the client side 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 workbook. It also obtains the corresponding object through the factory mode method. This method requires two parameters, one is the name of the worksheet, and the other is For the location of the worksheet in the workbook, 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 It is also ready, and you can start cooking!", all you have to do now is to instantiate the basic Excel data types provided by the API and add them to the worksheet, refer to the following code snippet:

//1 .Add Label object
jxl .write.Label labelC = new jxl .write.Label(0, 0, "This is a Label cell");
ws.addCell(labelC);
//Add an object with font
formatting jxl . write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES, 18,
WritableFont.BOLD, true);
jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
jxl.write.Label labelCF = new jxl.write.Label(1, 0, "This is a Label Cell",
wcfF);
ws.addCell(labelCF);
//添加带有字体颜色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.添加Number对象
jxl.write.Number labelN = new jxl.write.Number(0, 1, 3.1415926);
ws.addCell(labelN);
//添加带有formatting的Number对象
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, wcfN);
ws.addCell(labelNF);
//3.添加Boolean对象
jxl.write.Boolean labelB = new jxl .write.Boolean (0, 2, false);
ws.addCell (labelB);
// 4. DateTime 对象
jxl .write.DateTime labelDT = new jxl .write.DateTime (0, 3, new java.util.Date ());
ws.addCell (labelDT);
// 带有 atting Formatting 的 DateFormat 对象
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 draw your attention here. The first point is that the location of the cell in the worksheet is already determined when the cell is constructed. Once created, the position of the cell cannot be changed, although the contents of the cell can be changed. The second point, the positioning of the cells is according to the following rules (column, row), and the subscripts start from 0, for example, A1 is stored in (0, 0), B1 is stored in (1, 0) .

Finally, don't forget to close the open Excel workbook object to free up the occupied memory, see the code snippet below:

//Write the Excel worksheet
wwb.write();
//Close the Excel workbook object
wwb.close();


This may be a little different from the operation of reading an Excel file. Before closing the Excel object, you must call the write() method first, because the previous operations are stored in the cache, so the content of the operation must be passed through this method. Save in file. If you close the Excel object first, you will only get an empty workbook.

Copy and update Excel workbook

Next , I will briefly introduce how to update an existing workbook, mainly the following two steps, the first step is to construct a read-only Excel workbook, and the second step is to use the created Excel workbook Create a new writable Excel workbook, refer to the following code snippet: (For the complete code, see ExcelModifying.java)

//Create a read-only Excel workbook object
jxl .Workbook rw = jxl .Workbook.getWorkbook(new File( sourcefile));
//Create a writable Excel workbook object
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile),
rw);
//Read the first worksheet
jxl .write.WritableSheet ws = wwb.getSheet(0);
//Get the first cell Object
jxl .write.WritableCell wc = ws.getWritableCell(0, 0);
//Determine the type of cell and make corresponding transformation
if(wc.getType() == CellType.LABEL)
{
Label l = (Label) wc;
    l.setString("The value has been modified.");
}
//Write to Excel object
wwb.write();
//Close
wwb.close();
//Close read-only Excel object Excel object
rw.close();


The reason why Excel objects are constructed in this way is entirely for efficiency reasons, because the above example is the APImain application. In order to improve performance, when reading the worksheet, some output information related to the data, all format information, such as: font, color, etc., are not processed, because our purpose is to obtain the value of the row data, both Without the decoration, it will not have any effect on the value of the row data. The only downside is that two identical worksheets will be kept in memory at the same time, so when the worksheet size is relatively large, it will take up a considerable amount of memory, but now it seems that the size of the memory is not a critical factor.

Once we get the writable worksheet object, we can update the cell object. Here we don't have to call the add() method provided by the API , because the cell is already in the worksheet, so we only need to Call the corresponding setXXX() method to complete the update operation.

Although the original formatting modification of the cell cannot be removed, we can still add new cell modification to make the content of the cell manifest in a different form.

The newly generated worksheet object is writable. In addition to updating the original cells, we can also add new cells to the worksheet, which is exactly the same as the operation in Example 2.

Finally, don't forget to call the write() method, write the updated content to the file, and then close the workbook object, there are two workbook objects to close, one is read-only and the other is writable.


Summary
This article is just an introduction to the methods commonly used in the Java Excel API . If you want to know more about the API , please refer to the API documentation or source code. Java Excel API is an open source project, please pay attention to its latest development. Interested friends can also apply to join this project, or give valuable opinions.

ReferencesJava

ExcelAPI Documentation

http://www.andykhan.com/jexcelapi/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326687831&siteId=291194637
jxl
API