javafx 导入excel
时间: 2023-11-29 20:46:18 浏览: 167
以下是使用JavaFX导入Excel的步骤:
1.首先,需要在pom.xml文件中添加以下依赖项:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
```
2.创建一个FileChooser对象,以便用户可以选择要导入的Excel文件。
```java
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Excel File");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Excel Files", "*.xlsx", "*.xls"));
File selectedFile = fileChooser.showOpenDialog(stage);
```
3.使用Apache POI库读取Excel文件并将其存储在ObservableList中。
```java
ObservableList<ObservableList<String>> data = FXCollections.observableArrayList();
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream); XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
ObservableList<String> rowData = FXCollections.observableArrayList();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
rowData.add(cell.getStringCellValue());
break;
case NUMERIC:
rowData.add(String.valueOf(cell.getNumericCellValue()));
break;
case BOOLEAN:
rowData.add(String.valueOf(cell.getBooleanCellValue())); break;
default:
rowData.add("");
break;
}
}
data.add(rowData);
}
workbook.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
```
4.将ObservableList中的数据显示在JavaFX表格中。
```java
TableView<ObservableList<String>> tableView = new TableView<>();
for (int i = 0; i < data.get(0).size(); i++) {
final int finalIdx = i;
TableColumn<ObservableList<String>, String> column = new TableColumn<>(String.valueOf(i + 1));
column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().get(finalIdx)));
tableView.getColumns().add(column);
}
tableView.setItems(data);
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)