java获取excel第一列有内容的总行数,不考虑之后列的的内容
时间: 2024-03-09 14:44:30 浏览: 60
你可以使用 Apache POI 库来读取 Excel 文件并获取第一列有内容的总行数。下面是一个示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelReader {
public static int getRowCount(String filePath, String sheetName) throws IOException {
FileInputStream inputStream = new FileInputStream(new File(filePath));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheet(sheetName);
int rowCount = 0;
for (Row row : sheet) {
Cell cell = row.getCell(0);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
rowCount++;
}
}
workbook.close();
inputStream.close();
return rowCount;
}
}
```
使用方式:
```java
String filePath = "path/to/excel/file.xlsx";
String sheetName = "Sheet1";
int rowCount = ExcelReader.getRowCount(filePath, sheetName);
System.out.println("Total rows: " + rowCount);
```
其中 `filePath` 是 Excel 文件的路径,`sheetName` 是要读取的工作表的名称,`rowCount` 是第一列有内容的总行数。注意,这里假设第一列是列索引为 0 的列。
阅读全文