@Test
public void testExcel(){
String str = "D:\\1.xlsx";
Workbook workbook = null;
File file = new File(str);
System.out.println(file.getName());
if (file.isFile()&&file.exists()){ //判断文件是否是文件以及存在
try {
FileInputStream fileInputStream = new FileInputStream(file);//文件流对象
try {
//可以先判断文件的格式 我的格式是XLSX的 所以我这里省略了
workbook = new XSSFWorkbook(fileInputStream); // 格式为Xlsx 的Excel
} catch (IOException e) {
e.printStackTrace();
try {
workbook = new HSSFWorkbook(fileInputStream);//格式为Xls 的Excel
} catch (IOException e1) {
e1.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Sheet sheet = workbook.getSheetAt(0);//读取第一个sheet页
int firstRowIndex =sheet.getFirstRowNum(); //第一行
int lastRowIndex = sheet.getLastRowNum(); //最后一行
System.out.println();
System.out.println(firstRowIndex);
System.out.println(lastRowIndex);
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex); //获得第一行的数据 rIndex=0
if (row != null) {
int firstCellIndex = row.getFirstCellNum();//第一列
int lastCellIndex = row.getLastCellNum();//最后一列
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex); //获得第一行第一列的数据 cIndex=0;
if (cell != null) {
System.out.println(cell.toString());
}
}
}
}
}
上述代码如有疑问 欢迎咨询!