要在Java中获取Excel数据,可以使用Apache POI库。以下是获取Excel数据的基本步骤:
- 导入Apache POI库的依赖项。在Maven项目中,可以在pom.xml文件中添加以下依赖项:
org.apache.poi poi 4.1.2 org.apache.poi poi-ooxml 4.1.2
- 创建一个
Workbook
对象,打开Excel文件:
File file = new File("path/to/excel.xlsx"); // 替换为实际的Excel文件路径 Workbook workbook = WorkbookFactory.create(file);
- 获取要读取的工作表:
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
- 遍历工作表中的每一行和每一列,并获取单元格的值:
for (Row row : sheet) { for (Cell cell : row) { String cellValue = https://www.yisu.com/ask/cell.getStringCellValue();"\t"); } System.out.println(); // 换行 }
完整代码示例:
import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ExcelReader { public static void main(String[] args) { try { File file = new File("path/to/excel.xlsx"); // 替换为实际的Excel文件路径 FileInputStream fis = new FileInputStream(file); Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 for (Row row : sheet) { for (Cell cell : row) { String cellValue = https://www.yisu.com/ask/cell.getStringCellValue();"\t"); } System.out.println(); // 换行 } workbook.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
注意:上述代码假设Excel文件的扩展名为.xlsx。如果Excel文件的扩展名为.xls,需要使用HSSFWorkbook
代替XSSFWorkbook
。