java 读取excel文件的数据源码demo
时间: 2023-09-13 15:13:00 浏览: 42
当然,这是一个使用 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 ExcelReaderDemo {
public static void main(String[] args) {
String excelFilePath = "path/to/your/excel/file.xlsx";
try (FileInputStream inputStream = new FileInputStream(excelFilePath);
Workbook workbook = new XSSFWorkbook(inputStream)) {
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
for (Row row : sheet) {
for (Cell cell : row) {
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING) {
System.out.print(cell.getStringCellValue() + "\t");
} else if (cellType == CellType.NUMERIC) {
System.out.print(cell.getNumericCellValue() + "\t");
} else if (cellType == CellType.BOOLEAN) {
System.out.print(cell.getBooleanCellValue() + "\t");
}
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,我们首先通过 FileInputStream 打开 Excel 文件,然后使用 XSSFWorkbook 类创建 Workbook 对象。接下来,我们使用 getSheetAt() 方法获取第一个工作表。然后,我们遍历每一行和每个单元格,并根据单元格的类型打印出相应的值。
请确保将 `path/to/your/excel/file.xlsx` 替换为你要读取的实际 Excel 文件的路径。
希望这个示例对你有所帮助!如有任何问题,请随时提问。