posts - 5,  comments - 7,  trackbacks - 0

Java解释Excel数据(jxl.jar包的使用)

关键字: java excel jxl.jar

jxl.jar 包
下载地址:
http://www.andykhan.com/jexcelapi/
真实下载地址:
http://www.andykhan.com/jexcelapi/download.html

网站上对它的特征有如下描述:
● 支持Excel 95-2000的所有版本
● 生成Excel 2000标准格式
● 支持字体、数字、日期操作
● 能够修饰单元格属性
● 支持图像和图表
应该说以上功能已经能够大致满足我们的需要。最关键的是这套API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。
搭建环境
将下载后的文件解包,得到jxl.jar,放入classpath,安装就完成了。

基本操作

一、创建文件
拟生成一个名为“测试数据.xls”的Excel文件,其中第一个工作表被命名为“第一页”,大致效果如下:

 1/*  
 2 * Created on Dec 30, 2007  
 3 *  
 4 * To change the template for this generated file go to  
 5 * Window>Preferences>Java>Code Generation>Code and Comments  
 6 */
  
 7package JExcelTest.standard;   
 8  
 9import java.io.*;    
10import jxl.*;    
11import jxl.write.*;    
12  
13/**  
14 * @author Ken  
15 *  
16 * To change the template for this generated type comment go to  
17 * Window>Preferences>Java>Code Generation>Code and Comments  
18 */
  
19public class CreateXLS {   
20  
21    public static void main(String[] args) {   
22        try {   
23            //open file.   
24            WritableWorkbook book = Workbook.createWorkbook(new File("d:/Test.xls"));   
25               
26            //create Sheet named "Sheet_1". 0 means this is 1st page.   
27            WritableSheet sheet = book.createSheet("Sheet_1"0);   
28               
29            //define cell column and row in Label Constructor, and cell content write "test".   
30            //cell is 1st-Column,1st-Row. value is "test".   
31            Label label = new Label(00"test");   
32            //add defined cell above to sheet instance.   
33            sheet.addCell(label);   
34               
35            //create cell using add numeric. WARN:necessarily use integrated package-path, otherwise will be throws path-error.   
36            //cell is 2nd-Column, 1st-Row. value is 789.123.   
37            jxl.write.Number number = new jxl.write.Number(10789.123);   
38            //add defined cell above to sheet instance.   
39            sheet.addCell(number);   
40               
41            //add defined all cell above to case.   
42            book.write();   
43            //close file case.   
44            book.close();   
45        }
 catch (Exception e) {   
46            e.printStackTrace();   
47        }
   
48    }
   
49}
  
50

 1/*  
 2 * Created on Dec 30, 2007  
 3 *  
 4 * To change the template for this generated file go to  
 5 * Window>Preferences>Java>Code Generation>Code and Comments  
 6 */
  
 7package JExcelTest.standard;   
 8  
 9import java.io.*;    
10import jxl.*;    
11import jxl.write.*;    
12  
13/**  
14 * @author Ken  
15 *  
16 * To change the template for this generated type comment go to  
17 * Window>Preferences>Java>Code Generation>Code and Comments  
18 */
  
19public class CreateXLS {   
20  
21    public static void main(String[] args) {   
22        try {   
23            //open file.   
24            WritableWorkbook book = Workbook.createWorkbook(new File("d:/Test.xls"));   
25               
26            //create Sheet named "Sheet_1". 0 means this is 1st page.   
27            WritableSheet sheet = book.createSheet("Sheet_1"0);   
28               
29            //define cell column and row in Label Constructor, and cell content write "test".   
30            //cell is 1st-Column,1st-Row. value is "test".   
31            Label label = new Label(00"test");   
32            //add defined cell above to sheet instance.   
33            sheet.addCell(label);   
34               
35            //create cell using add numeric. WARN:necessarily use integrated package-path, otherwise will be throws path-error.   
36            //cell is 2nd-Column, 1st-Row. value is 789.123.   
37            jxl.write.Number number = new jxl.write.Number(10789.123);   
38            //add defined cell above to sheet instance.   
39            sheet.addCell(number);   
40               
41            //add defined all cell above to case.   
42            book.write();   
43            //close file case.   
44            book.close();   
45        }
 catch (Exception e) {   
46            e.printStackTrace();   
47        }
   
48    }
   
49}
  
50

编译执行后,会在当前位置产生一个Excel文件。

二、读取文件
以刚才我们创建的Excel文件为例,做一个简单的读取操作,程序代码如下:
 1/*  
 2 * Created on Dec 30, 2007  
 3 *  
 4 * To change the template for this generated file go to  
 5 * Window>Preferences>Java>Code Generation>Code and Comments  
 6 */
  
 7package JExcelTest.standard;   
 8  
 9import java.io.*;   
10import jxl.*;   
11  
12/**  
13 * @author Ken  
14 *  
15 * To change the template for this generated type comment go to  
16 * Window>Preferences>Java>Code Generation>Code and Comments  
17 */
  
18public class ReadXLS {   
19  
20    public static void main(String[] args) {   
21        try {   
22            Workbook book = Workbook.getWorkbook(new File("d:/Test.xls"));   
23            //get a Sheet object.    
24            Sheet sheet = book.getSheet(0);   
25            //get 1st-Column,1st-Row content.   
26            Cell cell = sheet.getCell(00);   
27            String result = cell.getContents();   
28            System.out.println(result);   
29            book.close();   
30        }
 catch (Exception e) {   
31            e.printStackTrace();   
32        }
   
33  
34    }
   
35}
  

 1/*  
 2 * Created on Dec 30, 2007  
 3 *  
 4 * To change the template for this generated file go to  
 5 * Window>Preferences>Java>Code Generation>Code and Comments  
 6 */
  
 7package JExcelTest.standard;   
 8  
 9import java.io.*;   
10import jxl.*;   
11  
12/**  
13 * @author Ken  
14 *  
15 * To change the template for this generated type comment go to  
16 * Window>Preferences>Java>Code Generation>Code and Comments  
17 */
  
18public class ReadXLS {   
19  
20    public static void main(String[] args) {   
21        try {   
22            Workbook book = Workbook.getWorkbook(new File("d:/Test.xls"));   
23            //get a Sheet object.    
24            Sheet sheet = book.getSheet(0);   
25            //get 1st-Column,1st-Row content.   
26            Cell cell = sheet.getCell(00);   
27            String result = cell.getContents();   
28            System.out.println(result);   
29            book.close();   
30        }
 catch (Exception e) {   
31            e.printStackTrace();   
32        }
   
33  
34    }
   
35}
  
36

程序执行结果:test

三、修改文件
利用jExcelAPI可以修改已有的Excel文件,修改Excel文件的时候,除了打开文件的方式不同之外,其他操作和创建Excel是一样的。下面的例子是在我们已经生成的Excel文件中添加一个工作表:
修改Excel的类,添加一个工作表
 1/*  
 2 * Created on Dec 30, 2007  
 3 *  
 4 * To change the template for this generated file go to  
 5 * Window>Preferences>Java>Code Generation>Code and Comments  
 6 */
  
 7package JExcelTest.standard;   
 8  
 9import java.io.*;   
10import jxl.*;   
11import jxl.write.*;   
12  
13/**  
14 * @author Ken  
15 *  
16 * To change the template for this generated type comment go to  
17 * Window>Preferences>Java>Code Generation>Code and Comments  
18 */
  
19public class UpdateXLS {   
20  
21    public static void main(String[] args) {   
22        try {   
23            //get file.   
24            Workbook wb = Workbook.getWorkbook(new File("d:/Test.xls"));   
25            //open a copy file(new file), then write content with same content with Test.xls.     
26            WritableWorkbook book =   
27                Workbook.createWorkbook(new File("d:/Test.xls"), wb);   
28            //add a Sheet.   
29            WritableSheet sheet = book.createSheet("Sheet_2"1);   
30            sheet.addCell(new Label(00"test2"));   
31            book.write();   
32            book.close();   
33        }
 catch (Exception e) {   
34            e.printStackTrace();   
35        }
   
36    }
   
37}
  

 1/*  
 2 * Created on Dec 30, 2007  
 3 *  
 4 * To change the template for this generated file go to  
 5 * Window>Preferences>Java>Code Generation>Code and Comments  
 6 */
  
 7package JExcelTest.standard;   
 8  
 9import java.io.*;   
10import jxl.*;   
11import jxl.write.*;   
12  
13/**  
14 * @author Ken  
15 *  
16 * To change the template for this generated type comment go to  
17 * Window>Preferences>Java>Code Generation>Code and Comments  
18 */
  
19public class UpdateXLS {   
20  
21    public static void main(String[] args) {   
22        try {   
23            //get file.   
24            Workbook wb = Workbook.getWorkbook(new File("d:/Test.xls"));   
25            //open a copy file(new file), then write content with same content with Test.xls.     
26            WritableWorkbook book =   
27                Workbook.createWorkbook(new File("d:/Test.xls"), wb);   
28            //add a Sheet.   
29            WritableSheet sheet = book.createSheet("Sheet_2"1);   
30            sheet.addCell(new Label(00"test2"));   
31            book.write();   
32            book.close();   
33        }
 catch (Exception e) {   
34            e.printStackTrace();   
35        }
   
36    }
   
37}
  
38

高级操作

一、 数据格式化
在Excel中不涉及复杂的数据类型,能够比较好的处理字串、数字和日期已经能够满足一般的应用。
字串格式化
字符串的格式化涉及到的是字体、粗细、字号等元素,这些功能主要由WritableFont和WritableCellFormat类来负责。假设我们在生成一个含有字串的单元格时,使用如下语句,为方便叙述,我们为每一行命令加了编号:
WritableFont font1= new WritableFont(WritableFont.TIMES,16,WritableFont.BOLD);

//设置字体格式为excel支持的格式
WritableFont font3=new WritableFont(WritableFont.createFont("楷体_GB2312"),12,WritableFont.NO_BOLD );
① WritableCellFormat format1=new WritableCellFormat(font1);
② Label label=new Label(0,0,”data 4 test”,format1)
③ 其中
I.指定了字串格式:字体为TIMES,字号16,加粗显示。WritableFont有非常丰富的构造子,供不同情况下使用,jExcelAPI的java-doc中有详细列表,这里不再列出。
II.处代码使用了WritableCellFormat类,这个类非常重要,通过它可以指定单元格的各种属性,后面的单元格格式化中会有更多描述。
III.处使用了Label类的构造子,指定了字串被赋予那种格式。 在WritableCellFormat类中,还有一个很重要的方法是指定数据的对齐方式,比如针对我们上面的实例,可以指定:
//把水平对齐方式指定为居中
format1.setAlignment(jxl.format.Alignment.CENTRE);
//把垂直对齐方式指定为居中
format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//设置自动换行
format1.setWrap(true);

二、单元格操作
Excel中很重要的一部分是对单元格的操作,比如行高、列宽、单元格合并等,所幸jExcelAPI提供了这些支持。这些操作相对比较简单,下面只介绍一下相关的API。
1、 合并单元格
WritableSheet.mergeCells(int m,int n,int p,int q);
作用是从(m,n)到(p,q)的单元格全部合并,比如:
WritableSheet sheet=book.createSheet(“第一页”,0);
//合并第一列第一行到第六列第一行的所有单元格
sheet.mergeCells(0,0,5,0);
合并既可以是横向的,也可以是纵向的。合并后的单元格不能再次进行合并,否则会触发异常。
2、 行高和列宽
WritableSheet.setRowView(int i,int height);
作用是指定第i+1行的高度,比如:
//将第一行的高度设为200
sheet.setRowView(0,200);
WritableSheet.setColumnView(int i,int width);
作用是指定第i+1列的宽度,比如:
//将第一列的宽度设为30
sheet.setColumnView(0,30);
三、操作图片
1public static void write()throws Exception{   
2        WritableWorkbook wwb=Workbook.createWorkbook(new File("c:/1.xls"));   
3        WritableSheet ws=wwb.createSheet("Test Sheet 1",0);   
4        File file=new File("C:\\jbproject\\PVS\\WebRoot\\weekhit\\1109496996281.png");   
5        WritableImage image=new WritableImage(14618,file);   
6        ws.addImage(image);   
7        wwb.write();   
8        wwb.close();   
9    }
  

1public static void write()throws Exception{   
2        WritableWorkbook wwb=Workbook.createWorkbook(new File("c:/1.xls"));   
3        WritableSheet ws=wwb.createSheet("Test Sheet 1",0);   
4        File file=new File("C:\\jbproject\\PVS\\WebRoot\\weekhit\\1109496996281.png");   
5        WritableImage image=new WritableImage(14618,file);   
6        ws.addImage(image);   
7        wwb.write();   
8        wwb.close();   
9    }
  

很简单和插入单元格的方式一样,不过就是参数多了些,WritableImage这个类继承了Draw,上面只是他构造方法的一种,最后一个参数不用了说了,前面四个参数的类型都是double,依次是 x, y, width, height,注意,这里的宽和高可不是图片的宽和高,而是图片所要占的单位格的个数,因为继承的Draw所以他的类型必须是double,具体里面怎么实现的我还没细看:)因为着急赶活,先完成功能,其他的以后有时间慢慢研究。以后会继续写出在使用中的心得给大家。

读:
读的时候是这样的一个思路,先用一个输入流(InputStream)得到Excel文件,然后用jxl中的Workbook得到工作薄,用Sheet从工作薄中得到工作表,用Cell得到工作表中得某个单元格.
InputStream->Workbook->Sheet->Cell,就得到了excel文件中的单元格
1String path="c:\\excel.xls";//Excel文件URL   
2InputStream is = new FileInputStream(path);//写入到FileInputStream   
3jxl.Workbook wb = Workbook.getWorkbook(is); //得到工作薄    
4jxl.Sheet st = wb.getSheet(0);//得到工作薄中的第一个工作表   
5Cell cell=st.getCell(0,0);//得到工作表的第一个单元格,即A1   
6String content=cell.getContents();//getContents()将Cell中的字符转为字符串   
7wb.close();//关闭工作薄   
8is.close();//关闭输入流  
9

1String path="c:\\excel.xls";//Excel文件URL   
2InputStream is = new FileInputStream(path);//写入到FileInputStream   
3jxl.Workbook wb = Workbook.getWorkbook(is); //得到工作薄    
4jxl.Sheet st = wb.getSheet(0);//得到工作薄中的第一个工作表   
5Cell cell=st.getCell(0,0);//得到工作表的第一个单元格,即A1   
6String content=cell.getContents();//getContents()将Cell中的字符转为字符串   
7wb.close();//关闭工作薄   
8is.close();//关闭输入流 

我们可以通过Sheet的getCell(x,y)方法得到任意一个单元格,x,y和excel中的坐标对应.
例如A1对应(0,0),A2对应(0,1),D3对应(3,2).Excel中坐标从A,1开始,jxl中全部是从0开始.
还可以通过Sheet的getRows(),getColumns()方法得到行数列数,并用于循环控制,输出一个sheet中的所有内容.

写:
往Excel中写入内容主要是用jxl.write包中的类.
思路是这样的:
OutputStream<-WritableWorkbook<-WritableSheet<-Label
这里面Label代表的是写入Sheet的Cell位置及内容.
 1OutputStream os=new FileOutputStream("c:\\test.xls");//输出的Excel文件URL   
 2WritableWorkbook wwb = Workbook.createWorkbook(os);//创建可写工作薄   
 3WritableSheet ws = wwb.createSheet("sheet1"0);//创建可写工作表   
 4Label labelCF=new Label(00"hello");//创建写入位置和内容   
 5ws.addCell(labelCF);//将Label写入sheet中   
 6Label的构造函数Label(int x, int y,String aString)xy意同读的时候的xy,aString是写入的内容.   
 7WritableFont wf = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD, false);//设置写入字体   
 8WritableCellFormat wcfF = new WritableCellFormat(wf);//设置CellFormat   
 9Label labelCF=new Label(00"hello");//创建写入位置,内容和格式   
10Label的另一构造函数Label(int c, int r, String cont, CellFormat st)可以对写入内容进行格式化,设置字体及其它的属性.   
11现在可以写了   
12wwb.write();   
13写完后关闭   
14wwb.close();   
15输出流也关闭吧   
16os.close;  

 1OutputStream os=new FileOutputStream("c:\\test.xls");//输出的Excel文件URL   
 2WritableWorkbook wwb = Workbook.createWorkbook(os);//创建可写工作薄   
 3WritableSheet ws = wwb.createSheet("sheet1"0);//创建可写工作表   
 4Label labelCF=new Label(00"hello");//创建写入位置和内容   
 5ws.addCell(labelCF);//将Label写入sheet中   
 6Label的构造函数Label(int x, int y,String aString)xy意同读的时候的xy,aString是写入的内容.   
 7WritableFont wf = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD, false);//设置写入字体   
 8WritableCellFormat wcfF = new WritableCellFormat(wf);//设置CellFormat   
 9Label labelCF=new Label(00"hello");//创建写入位置,内容和格式   
10Label的另一构造函数Label(int c, int r, String cont, CellFormat st)可以对写入内容进行格式化,设置字体及其它的属性.   
11现在可以写了   
12wwb.write();   
13写完后关闭   
14wwb.close();   
15输出流也关闭吧   
16os.close; 

OK,只要把读和写结合起来,就可以在N个Excel中读取数据写入你希望的Excel新表中,还是比较方便的.

下面是程序一例:
 1sql = "select * from tablename";   
 2rs = stmt.executeQuery(sql);   
 3  
 4//新建Excel文件   
 5String filePath=request.getRealPath("aaa.xls");   
 6File myFilePath=new File(filePath);   
 7if(!myFilePath.exists())   
 8myFilePath.createNewFile();   
 9FileWriter resultFile=new FileWriter(myFilePath);   
10PrintWriter myFile=new PrintWriter(resultFile);   
11resultFile.close();   
12  
13        //用JXL向新建的文件中添加内容   
14    OutputStream outf = new FileOutputStream(filePath);   
15        jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(outf);   
16        jxl.write.WritableSheet ws = wwb.createSheet("sheettest"0);   
17  
18int i=0;   
19        int j=0;   
20  
21for (int k = 0; k < rs.getMetaData().getColumnCount(); k++{   
22    ws.addCell(new Label(k,0,rs.getMetaData().getColumnName(k+1)));   
23}
   
24  
25while(rs.next()){   
26    out.println(rs.getMetaData().getColumnCount());   
27  
28for (int k = 0; k < rs.getMetaData().getColumnCount(); k++{   
29ws.addCell(new Label(k,j+i+1,rs.getString(k+1)));   
30    }
     
31  
32 i++;   
33}
   
34wwb.write();   
35    wwb.close();   
36}catch(Exception e){e.printStackTrace();}   
37finally{   
38  
39rs.close();   
40conn.close();   
41}
   
42  
43response.sendRedirect("aaa.xls"); 
posted on 2008-11-25 13:08 Vincent-chen 阅读(2283) 评论(0)  编辑  收藏 所属分类: PrintJXL

只有注册用户登录后才能发表评论。


网站导航: