Java Excel API Usage


Full excavation Java Excel API Usage
 
 

Author : Anonymous  Source : InterNet  Joined : 2005-1-28

 Windows operating systems friend of Excel (spreadsheet) will not be unfamiliar, but to use the Java language to manipulate Excel file is not an easy task. In Web applications increasingly popular today, needs to operate the Excel files through the Web more and more intense, the more popular action is to create a CSV (comma separated values) file in the JSP or Servlet and this file MIME, text / csv type returned to the browser, then the browser calls and display Excel CSV file. So just to say you can have access to Excel files, but can not really manipulate Excel files, this article will give you a surprise, to introduce an open source project, Java Excel API, you can use it to easily manipulate Excel files.

  Java Excel API Profile

  Java Excel is an open source project, you can read the contents of Excel files through its Java developers to create new Excel files, update Excel file that already exists. Using this API non-Windows operating systems can also be used to handle Excel data table by pure Java applications. Because it is written in Java, so we can call the API to enable access to Excel data table by JSP, Servlet in Web applications.

  Stable version is now released V2.0, provides the following functions:

   reading data from a file format in Excel 95, 97; 
   read Excel formulas (read after 97 Excel formulas); 
   generating an Excel spreadsheet ( format Excel 97); 
   support for fonts, numbers, date format; 
   support cell shadowing, and color manipulation; 
   modify existing data tables; 

  not yet support the following features, but soon it will provide:

   Chart can not be read; 
   can be read, but can not generate the formula, the last calculated value of any type can be read formula; 
 
   Application Example

  1, the Excel file is read from the data table

  Java Excel API may be a file from the local file system (.xls), it can also be read from an Excel spreadsheet input stream. Excel spreadsheet to read the first step is to create the Workbook (term: workbook), the following code fragment illustrates how to complete the operation code, see :( ExcelReading.java)
 
the java.io. * Import;
Import JXL *;.
... ... ... ...
the try
{
// Construction Workbook object, read-only Workbook object
// Create Workbook directly from the local file
// Create Workbook from the input stream
InputStream is = new FileInputStream (sourcefile );
jxl.Workbook Workbook.getWorkbook RWB = (IS);
}
the catch (Exception E)
{
e.printStackTrace ();
}

  Once the Workbook is created, we will be able to access it through Excel Sheet (term: worksheet). Reference to the following code fragment:
 
// Get the first table Sheet
Sheet rs = rwb.getSheet (0);

  We can pass the name Sheet to access it, it can also be accessed through the index. If accessed by subscript, then point to note is the index from 0, just like array.

  Once the Sheet, we can access Excel Cell (term: cells) through it. Reference to the following code fragment:
 
//获取第一行,第一列的值
Cell c00 = rs.getCell(0, 0);
String strc00 = c00.getContents();

//获取第一行,第二列的值
Cell c10 = rs.getCell(1, 0);
String strc10 = c10.getContents();

//获取第二行,第二列的值
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 only the value acquired Cell, we can conveniently be getContents () method, which can be any type of Cell values are returned as a string. Sample code Cell (0, 0) is a text type, Cell (1, 0) is a digital type, Cell (1,1) is a date type, by the getContents (), return values are three types of character.

  If you need to know the exact type of Cell contents, API also provides a range of methods. Reference to the following code fragment:
 
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 Cell object can be obtained by getType () method of the cell type, then the type of the API provided substantially match cast to the appropriate type, and finally call the appropriate value of the getXXX method (), can be obtained determining the type of the value. API provides the following basic types, the data format corresponding to Excel, as shown below:

  the specific meaning of each type, see 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 objects to the release process of reading the data table in the memory space occupied, it is particularly important when reading large amounts of data . With reference to the following code fragment:
 
// when the operation is completed, close the object, releasing the memory space occupied
rwb.close ();

  Java Excel API provides a number of ways to access Excel data table, where I only briefly introduce a few common methods, other methods, please refer to Java Excel API document in the appendix.
Workbook class provides methods

  1. int getNumberOfSheets ()

  number obtained workbook (Workbook) worksheet (Sheet), the example:
 
jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile));
int sheets = rwb.getNumberOfSheets();

  2. Sheet [] getSheets ()

  Returns the workbook (the Workbook) worksheet (Sheet) an array of objects, examples:
 
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, it seems to be nothing much effect.
 
jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile));
String apiVersion = rwb.getVersion();

  Sheet interface provides methods

  1) String getName ()

  Gets the name of the Sheet, an example:
 
jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile));
jxl.Sheet rs = rwb.getSheet(0);
String sheetName = rs.getName();

  2) int getColumns ()

  Gets Sheet total number of columns in the table included in the 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)

  Get all cells in a column, the cell returns an array of objects, examples:
 
jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile));
jxl.Sheet rs = rwb.getSheet(0);
Cell[] cell = rs.getColumn(0);

  4) int getRows ()

  Get the number of rows in the table contained Sheet, an 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)

  acquiring all the cells of a row, it returns the cell object array unit, example sub-:
 
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)

  acquiring a specified cell object reference, it should be noted that the two parameters, a first number of columns, and the second is the number of rows, which is normally the rows and columns the combination is somewhat different.
 
jxl.Workbook rwb = jxl.Workbook.getWorkbook(new File(sourcefile));
jxl.Sheet rs = rwb.getSheet(0);
Cell cell = rs.getCell(0, 0);

  2, generate a new Excel workbook

  The following code is mainly to tell you how to build a simple Excel worksheet, where the contents of the cell is without any modifications (such as: font, color, etc.), all content written as a string. (See complete code ExcelWriting.java)

  reading Excel worksheet similar to first create a workbook that can be written (Workbook) Workbook object using the class factory method to note here it is that the plant only via the API provided the method of creating the Workbook, but can not use a constructor WritableWorkbook because class constructor is protected WritableWorkbook type. Sample code fragment is as follows:
 
import java.io.*;
import jxl.*;
import jxl.write.*;
… … … …
try
{
//构建Workbook对象, 只读Workbook对象
//Method 1:创建可写入的Excel工作薄
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile));

//Method 2:将WritableWorkbook直接写入到输出流
/*
OutputStream os = new FileOutputStream(targetfile);
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os);
*/
}
catch (Exception e)
{
e.printStackTrace();
}

  API provides two ways to handle the output stream can be written, a direct generates a local file, if the file name with full path if not, the default file is positioned in the current directory, then if the file name with full path , the resulting Excel file will be positioned in the appropriate directory; another Excel object is written directly to the output stream, for example: a user to access the Web server through a browser, if the HTTP header set correctly, the browser automatically call client Excel application to display dynamically generated Excel spreadsheets.

  The next step is to create a worksheet, the worksheet to create a method and a method to create thin work almost the same, the corresponding object is also obtained by the factory mode, the method requires two parameters is a name of the worksheet, and the other is worksheet in the workbook positions, reference to the following code fragment:
 
//创建Excel工作表
jxl.write.WritableSheet ws = wwb.createSheet("Test Sheet 1", 0);

"这锅也支好了,材料也准备齐全了,可以开始下锅了!",现在要做的只是实例化API所提供的Excel基本数据类型,并将它们添加到工作表中就可以了,参考下面的代码片段:
//1.添加Label对象
jxl.write.Label labelC = new jxl.write.Label(0, 0, "This is a Label cell");
ws.addCell(labelC);

//添加带有字型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);

//添加带有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 things we have to get attention. First, when constructing a cell, cell location in the worksheet has been determined. Once created, the position of the cell is not able to change, although the contents of the cell can be changed. Second, positioning the cell in accordance with this law the following (column, row), and subscripts are from 0, for example, A1 is stored in the (0, 0), Bl is stored in the (1, 0) .

  Finally, do not forget to close the Excel workbook object is opened to release the memory occupied, see the following code fragment:
 
// write Exel worksheet
wwb.write ();

// Close Excel workbook objects
wwb.close ();

  This may be related to the read operation Excel files have different Shaoshao, before closing the Excel object, you must first call the write () method, because the contents of the previous operations are stored in the cache, so this method will operate stored in a file. If you turn off the Excel object, you can only get a blank workbook up.

  3, copy, update Excel workbook

  followed by a brief overview of how to update an existing workbook, mainly following a two step process, the first step is to construct read-only Excel workbook, the second step is the use of Excel has been created Create a new workbook writable Excel workbook, with reference to the following complete code snippet :( see ExcelModifying.java)
 
//创建只读的Excel工作薄的对象
jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(sourcefile));

//创建可写入的Excel工作薄对象
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File(targetfile), rw);

//读取第一张工作表
jxl.write.WritableSheet ws = wwb.getSheet(0);

//获得第一个单元格对象
jxl.write.WritableCell wc = ws.getWritableCell(0, 0);

//判断单元格的类型, 做出相应的转化
if(wc.getType() == CellType.LABEL)
{
Label l = (Label)wc;
l.setString("The value has been modified.");
}

//写入Excel对象
wwb.write();

//关闭可写入的Excel对象
wwb.close();

//关闭只读的Excel对象
rw.close();

  The reason for using the Excel object built this way, simply because the reasons of efficiency, as the example above is the main application API. To improve performance, while the worksheet is read, some of the information associated with the data output, all the formatting information, such as: font, color, etc., is not to be treated, because our purpose is to get the value of the line data, both so no modification, nor will the line of what impact the value of the data. The only downside is that in memory simultaneously save two same worksheet, worksheet so that when the volume is relatively large, will take up considerable memory, but the memory of what now seems the key factor is not the size.

  Once you get the worksheet objects that can be written, we can carry out the operation of the cell object update, and here we do not have to add API calls provided by () method, because the cells in the worksheet which has been, so we just need to call the appropriate setXXX () method, you can complete update of the operation.

  The original formatted cells to make modifications are not removed, we can add a new cell to modify, so that the contents of the cell performance in different forms.

  New worktable objects are written, in addition to update the original unit we particularly, may be added to a new cell in the worksheet, the operation of Example 2 which is exactly the same.

  Finally, do not forget to call write () method, the updated contents are written to a file, and then close the workbook objects, there are two objects you want to close the workbook, a read-only, the other is written.

Guess you like

Origin blog.csdn.net/wxmwzz/article/details/91348378