解决方法如下:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ApachePOIExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("path/to/your/excel/file.xlsx");
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
// 获取最后一行的行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
if (row != null) {
// 获取每一行的单元格数量
int lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
if (cell != null) {
// 读取单元格的值
String cellValue = cell.getStringCellValue();
System.out.println("Cell Value: " + cellValue);
}
}
}
}
// 关闭Workbook和文件流
workbook.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码使用Apache POI库读取Excel文件的内容,并在每一行的每个单元格中打印出单元格的值。在代码的最后,通过调用workbook.close()
和fis.close()
方法关闭Workbook和文件流,确保在读取行后退出。