一、JExcel介绍
JExcel是java对Excel进行操作的包,可以实现创建一个Excel并写入或读取Excel的数据等操作; JExcel的主要类为: (1)Workbook:工作簿 (2)WritableWorkbook:可写工作簿 (3)Sheet:表单; (4)WritableSheet:可写表单; (5)Label:单元格;
二、Java写入Excel
写入test.xls数据代码:
[java] view plain copy
- package com.xiazdong;
-
- import java.io.File;
-
- import jxl.Sheet;
- import jxl.Workbook;
- import jxl.write.Label;
- import jxl.write.WritableSheet;
- import jxl.write.WritableWorkbook;
-
- public class CreateTest {
-
- public static void main(String[] args) throws Exception{
- String str[][] = {{"xiazdong","12345"},{"xzdong","54321"}};
- File f = new File("test.xls");
- WritableWorkbook workbook = Workbook.createWorkbook(f);
- WritableSheet sheet = workbook.createSheet("sheet1", 0);
- Label lab = null;
- for(int i=0;i<str.length;i++){
- for(int j=0;j<str.length;j++){
- lab = new Label(j,i,str[j]); //Label(col,row,str);
- sheet.addCell(lab);
- }
- }
- workbook.write();
- workbook.close();
- }
-
- }
注意:Label中构造函数的参数,第一个参数是column,第二个参数是row,因此如果要插入第一行第二列,则(1,0); 总结:WritableWorkbook和WritableSheet都用于写入Excel文件;读取通过Workbook和Sheet执行;
三、读取Excel数据
读取test.xls中数据并显示代码:
[java] view plain copy
- package com.xiazdong;
-
- import java.io.File;
-
- import jxl.Sheet;
- import jxl.Workbook;
-
- public class CreateTest {
-
- public static void main(String[] args) throws Exception{
- Workbook workbook = Workbook.getWorkbook(new File("test.xls"));
- Sheet sheet[] = workbook.getSheets();
- String lab = null;
- for(int a=0;a<sheet.length;a++){
- for(int i=0;i<sheet[a].getRows();i++){
- for(int j=0;j<sheet[a].getColumns();j++){
- lab = sheet[a].getCell(j,i).getContents();
- System.out.print(lab+"、");
- }
- System.out.println();
- }
- }
-
- }
-
- }
通过JXL可以很方便地进行对于Excel文件的读取和写入;
|