在Java中读取Excel表的数据,可以使用Apache POI库来实现。Apache POI是一个流行的Java库,用于读写Microsoft Office文件,包括Excel文件。
以下是一个简单的示例代码,演示如何使用Apache POI来读取Excel表的数据:
import java.io.FileInputStream;import java.io.IOException;import org.apache.poi.ss.usermodel.*;public class ExcelReader {public static void main(String[] args) {try {// 打开Excel文件FileInputStream fis = new FileInputStream("path/to/excel.xlsx");// 创建工作簿对象Workbook workbook = WorkbookFactory.create(fis);// 获取第一个工作表Sheet sheet = workbook.getSheetAt(0);// 遍历工作表的每一行for (Row row : sheet) {// 遍历行的每一列for (Cell cell : row) {// 根据单元格的类型读取数据switch (cell.getCellType()) {case STRING:System.out.print(cell.getStringCellValue() + "\t");break;case NUMERIC:System.out.print(cell.getNumericCellValue() + "\t");break;case BOOLEAN:System.out.print(cell.getBooleanCellValue() + "\t");break;default:System.out.print("\t");}}System.out.println();}// 关闭文件流fis.close();} catch (IOException e) {e.printStackTrace();}}}请注意,在上述代码中,你需要修改"path/to/excel.xlsx"为实际的Excel文件路径。此外,代码中假设第一个工作表是要读取的工作表。如果需要读取其他工作表,可以使用workbook.getSheetAt(index)方法来获取对应的工作表,其中index表示工作表的索引,从0开始计数。
另外,需要在项目中引入Apache POI库的相关依赖,可以通过Maven或Gradle等构建工具来完成。具体的依赖配置可以参考Apache POI官方文档。