java poi获取excel单元格的值
时间: 2023-08-08 14:08:25 浏览: 63
你可以使用 Apache POI 库来获取 Excel 单元格的值。下面是一个示例代码,演示如何使用 POI 获取单元格的值:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) {
String filePath = "path/to/your/excel/file.xlsx"; // Excel 文件的路径
try {
FileInputStream fis = new FileInputStream(filePath);
Workbook workbook;
if (filePath.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(fis); // 读取 .xlsx 格式的文件
} else if (filePath.endsWith(".xls")) {
workbook = new HSSFWorkbook(fis); // 读取 .xls 格式的文件
} else {
throw new IllegalArgumentException("The specified file is not Excel file");
}
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
for (Row row : sheet) {
for (Cell cell : row) {
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING) {
System.out.println(cell.getStringCellValue());
} else if (cellType == CellType.NUMERIC) {
System.out.println(cell.getNumericCellValue());
} else if (cellType == CellType.BOOLEAN) {
System.out.println(cell.getBooleanCellValue());
}
// 可以根据需要处理其他类型的单元格值
}
}
workbook.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你需要将 `filePath` 替换为你自己的 Excel 文件路径。这段代码会打印出 Excel 文件中每个单元格的值。根据单元格的类型,你可以使用不同的方法来获取对应的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)