首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

jxl 课程

2012-10-21 
jxl 教程@author YHCJava Excel API Tutorial 当你需要访问工作簿时, 你可以使用这个去访问个别的工作簿.

jxl 教程

@author YHC

Java Excel API Tutorial


 当你需要访问工作簿时, 你可以使用这个去访问个别的工作簿.这些的下标都是从0开始 第一个工作簿是0, 第二个工作簿是1,等等.... (你也可以使用API通过名称去得到工作簿(Sheet)对象). 

Sheet sheet = workbook.getSheet(0);
当你有一个工作簿时,你然后可以开始访问单元格.你可以检索单元格内容,当内容是String类型时你可以使用简便的放法getContents() . 在下面示例代码, A1是一个text类型单元格, B2是一个数值类型和 C2 是一个date类型的单元格. 这些单元格的内容可以如下方式访问

Cell a1 = sheet.getCell(0,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(); 

// 针对字符串的操作....
...
  在demo示例程序中CSV.java 和 XML.java 使用简便方法 getContents() 方便输出Excel内容. 

 然而在需要在访问单元格内容时需要精确的类型时 例如. 如同一个数值(numerical)或者一个日期值(date), 然后检索单元格必须转换为正确的类型和和调用适当的方法.以下示例代码片段jxl从一个Excel中检索一个真是的java double类型的数据和java.util.Date对象. 出于完备性Label也可以转换为其正确的类型 ,虽然在实践中没有什么不同. 这个示例也阐明如何验证单元格(cell)是你期待的类型,这个在你验证Excel中的单元格(cell)是否在正确的位置时非常实用, . 

String stringa1 = null; 
double numberb2 = 0; 
Date datec2 = null; 

Cell a1 = sheet.getCell(0,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(); 


// 对日期数据和double类型数据操作 ....
...
  当你完成处理所有单元格时,使用close()方法.释放任何分配使用内存 ,当读取Excel时特别重要,尤其是读取较大Excel

// 最后 - 关闭workbook和释放内存
workbook.close();

          


接下来就是为workbook创建sheet. 重申一下, 这是一个工厂方法, 需要传入sheet名称和位置然后将占据在工作薄中.以下代码片段创建一个sheet 名称为"First Sheet" 在第一个. 

WritableSheet sheet = workbook.createSheet("First Sheet", 0);
现在剩余的就是添加单元格到工作表中了. 这个简单的示例添加单元格到sheet.以下代码片段放置一个label到单元格 A3, 和数字 3.14159 到单元格 D5. 

Label label = new Label(0, 2, "A label record"); 
sheet.addCell(label); 

Number number = new Number(3, 4, 3.1459); 
sheet.addCell(number);

这里有许多地方需要注意. 首先, 在sheet中的单元格位置需要指定作为构造函数的一部分. 一旦创建, 不能改变单元格的位置, 虽然单元格的内容可以更改. 


另外一个需要注意的地方,单元格的位置指定为(列,行),他们的下标是从0开始的整数- A1 通过 (0,0)代表, B1 通过 (1,0), A2 通过 (0,1) 和..... 

一旦你完成添加sheet和单元格到workbook中,你要调用write()方法在workbook,然后关闭文件. 最后步骤生成输出文件(output.xls ) 可以通过读取Excel. 如果你调用close()方法而没有在其之前调用write(),一个完整的空文件将生成. 

... 
//所有sheet和cell添加后.现在写出workbook 
workbook.write(); 
workbook.close();
  


Label label3 = new Label(2, 0, "Another Arial 10 point label", arial10format); 
sheet.addCell(label3);
这里创建另一个label,使用相同的格式在单元格C1中. 

因为单元格样式对象是共享的, 不能改变单元格格式化对象内容. (如果这是允许的, 然后改变对象内容可能会有不可预见的后果在其余的工作簿). 以便于改变一个特定的单元格的显示方式,API允许你分配一个新的样式到一个单元格上. 

WritableFont对象的构造方法有很多重载,通过示例, 以下代码片段创建一个 label 里面字体为TIMES 字号是16, 加粗和分配其位置为 D1.
//创建一个单元格 字体为TIMES 字号是16 加粗
WritableFont times16font = new WritableFont(WritableFont.TIMES, 16, WritableFont.BOLD, true); 
WritableCellFormat times16format = new WritableCellFormat (times16font); 

// 创建 label, 指定内容和格式 specifying content and format 
Label label4 = new Label(3,0, "Times 16 bold italic label", times16format); 
sheet.addCell(label4);

 由于时间原因,之后更新......


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);



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.


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 is an ordinary writable 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.




The build.xml specifies a number of targets. To totally rebuild the whole application, including the javadoc documentation, then obtain a command line prompt within the 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 out common jxl


Accessing the input stream directly means that the HTTP information is present. The first thing to do is strip off this redundant 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 are supported

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 (eg. System.out.print(date)) the JVM will perform timezone adjustment calculations. If you are located in EST zone (which is GMT - 5 hours) java will subtract 5 hours from the date - so the Date object instead of being 00:00 20/08/2003 becomes 19:00 19/08/2003. Because java recognizes you only want a date and not 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 used internally 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, rather 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 won't necessarily reference the correct sheet, and could even cause Excel to crash

1楼liwenqiang758昨天 17:04
好东西,就是没译完,要是全部都译了就更是好东西!
Re: yhc13429826359昨天 17:15
回复liwenqiang758n呵呵,下次继续更新,估计还更新3次就完了,不准或者错误的地方请多多指教.

热点排行