packageq;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;public classff
{public static void main(String[] args) throwsIOException
{
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= newXSSFWorkbook(inputStream);
}else if ( fileExtensionName.equals(".xls") )
{
workBook= newHSSFWorkbook(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
}
}