Java读写Excel

本文主要演示如何使用JavaExcel API来读写Excel文件。
支持Excel 95, 97, 2000, XP, 2003 的制表页。
jexcelapi下载地址:http://jexcelapi.sourceforge.net/,
然后把jxl.jar加到你的Java的classpath中。
可用于Selenium WebDriver从excel中读取测试用例数据

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExecuteExcel {
//http://jexcelapi.sourceforge.net/
public void readExcel(String inputFile) {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet 
            Sheet sheet = w.getSheet(0);
            for(int j=0; j <sheet.getColumns();j++) {
                for(int i=0; i<sheet.getRows();i++) {
                //读Excel的单元格类实例,通过sheet.getCell(row,col)获得,通过Cell的get方法可以获取每个单元格的格式,字体,内容等等
                Cell cell = sheet.getCell(j, i); 
                System.out.println("第"+(i+1)+"行第"+(j+1)+"列,数据格式:"+cell.getType()+";数据内容:"+cell.getContents()); 
                } 
            } 
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public void writeExcel(String inputFile,int row,int colum, String content)  {
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(inputFile);
WritableWorkbook writableWorkbook = Workbook.createWorkbook(fileOutputStream);
WritableSheet writableSheet = writableWorkbook.createSheet("Excel", 0);
Label label = new Label(colum, row, content);
writableSheet.addCell(label);
   writableWorkbook.write();
writableWorkbook.close();
fileOutputStream.close();
catch (FileNotFoundException e) {e.printStackTrace();} 
catch (IOException e) {e.printStackTrace();} 
catch (RowsExceededException e) {e.printStackTrace();} 
catch (WriteException e) {e.printStackTrace();}

}

public static void main(String[] args) {
ExecuteExcel test = new ExecuteExcel();
        test.readExcel("d:/euro2012.xls"); 
//test.writeExcel("d:/euro2012.xls",2,5,"11ppp"); 
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值