直接上代码:
```java
package com.example.excel;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javafx.scene.control.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReder {
public static void main(String[] args) throws IOException {
String excelPath = "F:\\sss.xlsx"; //文件位置
String sheetName = "001"; //文件里表名
try{
FileInputStream excelFile = new FileInputStream(excelPath); //创建输入流
XSSFWorkbook workbook = new XSSFWorkbook(excelFile); //
XSSFSheet excelSheet = workbook.getSheet(sheetName);
int rows = excelSheet.getPhysicalNumberOfRows(); //行数
int cols = excelSheet.getRow(0).getPhysicalNumberOfCells();//列数
for(int row = 0;row< rows; ++row){//行数循环
for (int col =0; col < cols; ++col){//列数循环
System.out.print(ReadData(excelSheet, row, col)+" ");
}
System.out.println();//行数换行
}
workbook.close();
}catch (FileNotFoundException e ){
System.out.println("找不到该文件");
}
}
public static String ReadData(XSSFSheet excelSheet, int row, int col){
try{
String CellData= "";
XSSFCell cell = excelSheet.getRow(row).getCell(col);
cell.setCellType(CellType.STRING);
CellData = cell.getStringCellValue();
return CellData;
}catch(Exception e){
return "";
}
}
}
效果图:
``