java按列读取excel
时间: 2024-03-20 13:36:59 浏览: 76
java读取excel
在Java中,可以使用Apache POI库来读取Excel文件。下面是按列读取Excel文件的一种实现方式:
1. 导入Apache POI库的依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 创建一个Workbook对象,打开Excel文件:
```java
FileInputStream fis = new FileInputStream("path/to/excel/file.xlsx");
Workbook workbook = new XSSFWorkbook(fis);
```
3. 获取第一个Sheet:
```java
Sheet sheet = workbook.getSheetAt(0);
```
4. 获取总行数和总列数:
```java
int rowCount = sheet.getPhysicalNumberOfRows();
int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();
```
5. 遍历每一列,读取数据:
```java
for (int col = 0; col < columnCount; col++) {
for (int row = 0; row < rowCount; row++) {
Row currentRow = sheet.getRow(row);
Cell cell = currentRow.getCell(col);
String cellValue = cell.getStringCellValue();
System.out.println("Column " + col + ", Row " + row + ": " + cellValue);
}
}
```
6. 关闭Workbook和文件输入流:
```java
workbook.close();
fis.close();
```
这样就可以按列读取Excel文件了。
阅读全文