java+selenium+new——POI读取excel文件——xls——xlsx结尾的文件——并进行操作
导入和环境相匹配的包:http://archive.apache.org/dist/poi/release/bin/
package q;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ff
{
public static void main(String[] args) throws IOException
{
String excelFilePath = "C:\\Users\\del\\Desktop\\Book1.xlsx";
File file = new File(excelFilePath); //根据上面的路径文件,创建一个文件对象
FileInputStream inputStream = new FileInputStream(file); //用于读取excel文件
Workbook workBook = null;
String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf(".")); //截取文件名,获取 . 后面(包括.)的内容
System.out.println(fileExtensionName); //打印内容.xlsx
if ( fileExtensionName.equals(".xlsx"))
{
workBook = new XSSFWorkbook(inputStream);
} else if ( fileExtensionName.equals(".xls") )
{
workBook = new HSSFWorkbook(inputStream);
}
Sheet Sheet = workBook.getSheet("用例"); //通过sheetName参数,生成Sheet对象
System.out.println(Sheet.getFirstRowNum()); //获取数据的第一行行号 0 //excel的行号和列号都是从0 开始
System.out.println(Sheet.getLastRowNum()); //获取数据的最后一行行号 6
System.out.println(Sheet.getRow(0).getCell(0).getStringCellValue());
System.out.println(Sheet.getRow(0).getCell(1).getStringCellValue());
System.out.println(Sheet.getRow(0).getCell(2).getStringCellValue());
System.out.println("------------------------------");
//System.out.println(Sheet.getRow(1).getCell(0).getStringCellValue()); //此处执行会发送错误,因为是数字类型,不是文字类型
System.out.println(Sheet.getRow(1).getCell(1).getStringCellValue());
System.out.println(Sheet.getRow(1).getCell(2).getStringCellValue());
System.out.println("------------------------------");
int totalRows = Sheet.getPhysicalNumberOfRows(); //获取总行数
System.out.println(totalRows); //返回总行数7
System.out.println("------------------------------");
int RowCells = Sheet.getRow(0).getPhysicalNumberOfCells(); //获取总列数
System.out.println(RowCells); //返回总列数3
System.out.println("------------------------------");
System.out.println(Sheet.getRow(2).getCell(0).toString()); //表格里是2,这里返回2.0
System.out.println("------------------------------");
System.out.println(Sheet.getRow(2).getCell(0).getNumericCellValue()); //表格里是2,这里返回2.0
// getStringCellValue
//java.lang.String getStringCellValue()
//以字符串形式获取单元格的值
//对于数字单元格,我们抛出异常。对于空白单元格,我们返回一个空字符串。对于不是字符串公式的FormulaCells,我们抛出异常。
//返回值:单元格的值作为字符串//
System.out.println("------------------------------");
Sheet.getRow(2).getCell(0).setCellType(Cell.CELL_TYPE_STRING); //设置单元格为string类型
System.out.println(Sheet.getRow(2).getCell(0).getStringCellValue()); //返回值为2
}
}
执行结果:
.xlsx
0
6
测试用例编号
输入对象1
输入对象2
-——————————————-
中国
航母
-——————————————-
7
-——————————————-
3
-——————————————-
2.0
-——————————————-
2.0
-——————————————-
2
还没有评论,来说两句吧...