本文主要演示如何使用JavaExcel API来读写Excel文件。
支持Excel 95, 97, 2000, XP, 2003 的制表页。
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());
}
}
writableWorkbook.write();
test.readExcel("d:/euro2012.xls");
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
} 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.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.writeExcel("d:/euro2012.xls",2,5,"11ppp");
}
}