《手把手教你》系列技巧篇(六十八)-java+ selenium自动化测试 - 读写excel文件 - 下篇(详细教程)
1.简介
今天继续操作Excle,小伙伴或者童鞋们是不是觉得宏哥会介绍第三种工具操作Excle,今天不介绍了,有两种就够用了,其实一种就够用了,今天主要是来介绍如何使用不同的数据类型读取Excel文件。在实际测试中,您可能不得不处理除String之外的多个数据类型的Excel文件数据。 在本教程中,我们将使用不同的数据类型读取Java中的excel文件。
2.准备不同数据类型的Excle
1.我们将尝试读取下面的excel,因为可以看出,excel在前四个单元中有Date,Number,Boolean和Label(常规字符串)数据。
2.把这个文件放到eclipse项目中,如下图所示:
3.JXL使用不同的数据类型读取Excel文件
3.1代码设计
1.新建一个OperateExcle.java的文件,输入如下代码。
3.2参考代码
package lessons; import java.io.File; import java.io.IOException; import jxl.BooleanCell; import jxl.Cell; import jxl.CellType; import jxl.DateCell; import jxl.LabelCell; import jxl.NumberCell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; /** * @author 北京-宏哥 * * @公众号:北京宏哥 * * 《手把手教你》系列技巧篇(六十八)-java+ selenium自动化测试 - 读写excel文件 -下篇(详细教程) * * 2022年2月15日 */ public class OperateExcle { public static void main(String[] args) { //从指定位置的文件创建工作簿对象;根据计算机上的位置更改文件的路径。 Workbook wrk1; try { wrk1 = Workbook.getWorkbook(new File(".\\Files\\test-data1.xls")); //获取工作簿中第一个工作表的引用 Sheet sheet1 = wrk1.getSheet(0); //使用工作表的getCel(int col, int row)方法获取对单元的引用 Cell cell1 = sheet1.getCell(0, 0); Cell cell2 = sheet1.getCell(1, 0); Cell cell3 = sheet1.getCell(2, 0); Cell cell4 = sheet1.getCell(3, 0); DateCell dCell = null; NumberCell nCell = null; BooleanCell bCell = null; LabelCell lCell = null; // 检查单元格内容的类型,并将该对象转换为适当的引用类型 if (cell1.getType() == CellType.DATE) dCell = (DateCell) cell1; if (cell2.getType() == CellType.NUMBER) nCell = (NumberCell) cell2; if (cell3.getType() == CellType.BOOLEAN) bCell = (BooleanCell) cell3; if (cell4.getType() == CellType.LABEL) lCell = (LabelCell) cell4; // 显示单元格内容 System.out.println("Value of Date Cell is: " + dCell.getDate()); System.out.println("Value of Number Cell is: " + nCell.getValue()); System.out.println("Value of Boolean Cell is: " + bCell.getValue()); System.out.println("Value of Label Cell is: " + lCell.getString()); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
3.3运行代码
1.运行代码,右键Run AS->Java Appliance,控制台输出,如下图所示:
5.小结
宏哥在代码运行的时候由于POIjar包的升级,有些变量可能会和旧的版本有区别,运行过程报错:java.lang.ClassNotFoundException: org.apache.commons.math3.util.ArithmeticUtils。可能是由于引入小数,需要数学的jar包,将其引入项目中成功解决报错。