import org.apache.poi.ss.usermodel.*;
import java.io.*;
public class ExcelRead2 {
public static void main(String[] args) {
readExcel("D:\\testjavaIO\\test11\\testcase.xlsx","Sheet1");
}
//读excel
public static void readExcel(String excelPath,String sheetName){
InputStream in = null;
try {
File file = new File(excelPath);
in = new FileInputStream(file);
Workbook workbook = WorkbookFactory.create(in);
Sheet sheet = workbook.getSheet(sheetName);
//获取标题行
Row firstRow = sheet.getRow(0);
//获取每行的列数
int lastCellNum = firstRow.getLastCellNum();
String[] titles = new String[lastCellNum];
for (int i = 0; i < lastCellNum; i++) {
Cell cell = firstRow.getCell(i);
String title = cell.getStringCellValue();
titles[i] = title;
}
//获取每行测试用例数据
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i < lastRowNum; i++) {
Row rowDate = sheet.getRow(i);
System.out.println("第" + i + "行数据:");
for (int j = 0; j < lastCellNum; j++) {
Cell cell = rowDate.getCell(j);
if(cell == null){
continue;
}
//设置单元格类型,解决Cannot get a STRING value from a NUMERIC cell报错
cell.setCellType(CellType.STRING);
String cellValue = cell.getStringCellValue();
//打印获取的数据
System.out.print("【" + titles[j] + " = " + cellValue + "】");
}
System.out.println();
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}