首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >修改按钮上的Excel单元格的值单击Apache POI & JavaFX

修改按钮上的Excel单元格的值单击Apache POI & JavaFX
EN

Stack Overflow用户
提问于 2018-10-15 06:04:21
回答 2查看 897关注 0票数 0

我正在尝试写一个简单的程序,创建一个小的应用程序,按一下按钮,将写入一个值到excel电子表格。

在下面的代码中,程序会将值25写入单元格,然后打印"25.0“。然后它会在单击按钮时将50写入单元格,并打印出"50.0",但一旦我关闭应用程序并打开电子表格,值25就会显示在单元格中。

代码语言:javascript
复制
package javafxapplication2;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;


public class JavaFXApplication2 extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
    XSSFWorkbook schedule = new XSSFWorkbook();
    XSSFSheet firstSheet = schedule.createSheet("Dis a sheet");
    XSSFRow firstRow = firstSheet.createRow(0);
    XSSFCell firstCell = firstRow.createCell(0);
    firstCell.setCellValue(25);
    System.out.println(firstCell.getRawValue());

    Button btn = new Button();
    btn.setText("Say 'Hello World'");

    btn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            writeInfoToCell(firstCell,50);
            System.out.println(firstCell.getRawValue());
        }

    });

    //});
    FileOutputStream out = new FileOutputStream(new File("schedule.xlsx"));
    schedule.write(out);
    out.close();
    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

}
public void writeInfoToCell(XSSFCell cell, int information){
    cell.setCellValue(information);
}
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}

有没有人能帮我解决这个问题?它必须与按钮的单击有关,因为如果我完全移除按钮,则值将正确写入单元格。

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-15 09:42:40

您的btn操作只写入XSSFCell,但您没有写入XSSFWorkbook

尝试:

代码语言:javascript
复制
btn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            FileOutputStream out = new FileOutputStream(new File("schedule.xlsx"));                 
            writeInfoToCell(firstCell,50);
            System.out.println(firstCell.getRawValue());
            schedule.write(out);
            out.close();
            }

        });
票数 1
EN

Stack Overflow用户

发布于 2018-10-15 06:44:56

对不起,但是,你的观点是,当你的应用程序再次运行时,你需要有一个空值,或者别的什么?

如果你的问题仅仅是“当打开时是干净的”,你可以在你的代码上放置一个简单的jquery,或者js并清理输入。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52807474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档