JExcel入门,JAVA读写Excel文件
(本人下的是jexcelapi_2_6_12.tar.gz,解压后将里面的jxl.jar复制到WEB-INF/lib目录下面即可)
Java Excel API的jar包可以通过以下URL获得:(推荐)
http://sourceforge.net/projects/jexcelapi/files/jexcelapi/2.6.6/jexcelapi_2_6_6.zip/download
(包括所有版本):http://sourceforge.net/projects/jexcelapi/files/
一、JExcel介绍
JExcel是Java对Excel进行操作的包,可以实现创建一个Excel并写入或读取Excel的数据等操作;
JExcel的主要类为:
(1)Workbook:工作簿
(2)WritableWorkbook:可写工作簿
(3)Sheet:表单;
(4)WritableSheet:可写表单;
(5)Label:单元格;
二、Java写入Excel
写入test.xls数据代码:
1 import java.io.File; 2 3 import jxl.Sheet; 4 import jxl.Workbook; 5 import jxl.write.Label; 6 import jxl.write.WritableSheet; 7 import jxl.write.WritableWorkbook; 8 9 public class CreateTest { 10 11 public static void main(String[] args) throws Exception{ 12 String str[][] = {{"xiazdong","12345"},{"xzdong","54321"}}; 13 File f = new File("test.xls"); 14 WritableWorkbook workbook = Workbook.createWorkbook(f); 15 WritableSheet sheet = workbook.createSheet("sheet1", 0); 16 Label lab = null; 17 for(int i=0;i<str.length;i++){ 18 for(int j=0;j<str[i].length;j++){ 19 lab = new Label(j,i,str[i][j]); //Label(col,row,str); 20 sheet.addCell(lab); 21 } 22 } 23 workbook.write(); 24 workbook.close(); 25 } 26 27 }
注意:Label中构造函数的参数,第一个参数是column,第二个参数是row,因此如果要插入第一行第二列,则(1,0);
总结:WritableWorkbook和WritableSheet都用于写入Excel文件;读取通过Workbook和Sheet执行;
三、读取Excel数据
读取test.xls中数据并显示代码:
1 import java.io.File; 2 3 import jxl.Sheet; 4 import jxl.Workbook; 5 6 public class CreateTest { 7 8 public static void main(String[] args) throws Exception{ 9 Workbook workbook = Workbook.getWorkbook(new File("test.xls")); 10 Sheet sheet[] = workbook.getSheets(); 11 String lab = null; 12 for(int a=0;a<sheet.length;a++){ 13 for(int i=0;i<sheet[a].getRows();i++){ 14 for(int j=0;j<sheet[a].getColumns();j++){ 15 lab = sheet[a].getCell(j,i).getContents(); 16 System.out.print(lab+"、"); 17 } 18 System.out.println(); 19 } 20 } 21 22 } 23 24 }
点点滴滴,终汇一海