我正在尝试写一个简单的程序,创建一个小的应用程序,按一下按钮,将写入一个值到excel电子表格。
在下面的代码中,程序会将值25写入单元格,然后打印"25.0“。然后它会在单击按钮时将50写入单元格,并打印出"50.0",但一旦我关闭应用程序并打开电子表格,值25就会显示在单元格中。
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);
}
}
有没有人能帮我解决这个问题?它必须与按钮的单击有关,因为如果我完全移除按钮,则值将正确写入单元格。
谢谢!
发布于 2018-10-15 09:42:40
您的btn操作只写入XSSFCell
,但您没有写入XSSFWorkbook
。
尝试:
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();
}
});
发布于 2018-10-15 06:44:56
对不起,但是,你的观点是,当你的应用程序再次运行时,你需要有一个空值,或者别的什么?
如果你的问题仅仅是“当打开时是干净的”,你可以在你的代码上放置一个简单的jquery,或者js并清理输入。
https://stackoverflow.com/questions/52807474
复制相似问题