java poi获取excel单元格的值
时间: 2023-08-08 07:08:25 浏览: 246
您可以使用Apache POI库来获取Excel单元格的值。下面是一个简单的示例代码:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) {
String filePath = "path/to/your/excel.xlsx";
String sheetName = "Sheet1";
int rowNum = 1; // 行号
int colNum = 2; // 列号
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
Sheet sheet = workbook.getSheet(sheetName);
Row row = sheet.getRow(rowNum);
Cell cell = row.getCell(colNum);
String cellValue = "";
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
}
}
System.out.println("Cell Value: " + cellValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
您需要将`filePath`变量设置为您的Excel文件的路径,`sheetName`变量设置为要读取的工作表的名称,以及`rowNum`和`colNum`变量设置为要读取的单元格的行号和列号。以上代码将输出所选单元格的值。请确保在项目中包含了Apache POI库的依赖。
阅读全文