我想使用java在excel文件中保存数据,但每次都替换以前的数据。我正在使用javafx来构建桌面应用程序

时间:2017-08-27 01:09:17

标签: java apache-poi

try {
    FileInputStream fIPS = new FileInputStream("excel.xls"); //Read the spreadsheet that needs to be updated
    HSSFWorkbook wb;
    HSSFSheet worksheet;
    if (fIPS.available() >= 512) {
        wb = new HSSFWorkbook(fIPS); //If there is already data in a workbook
        worksheet = wb.getSheetAt(0);
    } else {
        wb = new HSSFWorkbook();    //if the workbook was just created
        worksheet = wb.createSheet("Data");
    }
    //Access the worksheet, so that we can update / modify it


    Row row1 = worksheet.getRow(0);
    //0 = row number
    // int r = row1.getRowNum();
    int i = 0;
    Cell c = row1.getCell(i);
    while (!(c == null || c.getCellType() == Cell.CELL_TYPE_BLANK)) {   //cell is empty
        i++;
        //   r++;
        c = row1.getCell(i);
    }
    Row rowx;

    int x = 0;
    for (CompletenessModel s : find()) {
        rowx = worksheet.createRow(x);

        // int rx = rowx.getRowNum();
        Cell cellx = rowx.createCell(i);   //0 = column number
        cellx.setCellValue(s.getDot());
        x++;
        //rx++;
    }


    fIPS.close(); //Close the InputStream
    FileOutputStream output_file = new
            FileOutputStream("test.xls");//Open FileOutputStream to write updates
    wb.write(output_file); //write changes
    output_file.close();  //close the stream

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

代码仅修改第0行数据。我希望尽可能多地添加记录。用户输入位于javafx textarea字段中。我正在使用列表来获取所有用户输入。我尝试过很多东西但是徒劳无功。用户输入进入系统并且一次只显示一条记录。当我关闭应用程序或再次重写输入时,删除excel文件中先前存储的数据并在那里写入新数据。

0 个答案:

没有答案