java 读取excel 文件
时间: 2024-08-10 21:01:48 浏览: 71
在Java中,我们可以使用Apache POI库来读取Excel文件,它是一个功能强大的API,支持多种版本的Microsoft Excel格式。以下是基本步骤:
1. **添加依赖**:首先,需要在项目中引入Apache POI的XSSF(XML-based API for reading and writing Microsoft Excel 2007+ .xlsx files)模块,如果使用Maven,可以在pom.xml文件中添加如下依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>latest version (check the official site)</version>
</dependency>
```
2. **创建读取对象**:通过`XSSFWorkbook`打开Excel文件:
```java
FileInputStream inputStream = new FileInputStream("path_to_your_file.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
```
3. **遍历工作表**:使用`workbook.getSheetAt(index)`获取指定索引的工作表,然后可以使用`Row`对象遍历行,`Cell`对象遍历单元格的值:
```java
Sheet sheet = workbook.getSheetAt(0); // 获取第一张表
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
// 其他数据类型处理...
}
}
System.out.println(); // 换行
}
```
4. **关闭资源**:读取完成后别忘了关闭输入流和工作簿:
```java
workbook.close();
inputStream.close();
```
阅读全文
相关推荐














