Write in the same file Excel

Hi ! I want to append to the same excel file every time when i export from my application. Can help me someone ?

public class ExcelFileService {
private final Logger logger = Logger.getLogger(getClass().getName());
private Workbook excel;
private static final String FILE_PATH = “C:\Users\User\Desktop\Book3.xlsx”;

public ExcelFileService() {
    try {
        this.excel = new Workbook(FILE_PATH);
    } catch (Exception e) {
        logger.info(e.getMessage());
    }
}

public void writeToFile() {
    WorksheetCollection worksheets = excel.getWorksheets();
    int serialSheetIndex = worksheets.add();

    Worksheet firstWorksheet = worksheets.get(serialSheetIndex);
    firstWorksheet.setName("Test");

    Cells cells = firstWorksheet.getCells();

    int maxDataRow = cells.getMaxDataRow();
    cells.get("A1").setValue("Firstname");
    cells.get("A2").setValue("John");
    cells.get("A3").setValue("Jane");
    cells.get("B1").setValue("Lastname");
    cells.get("B2").setValue("Mikey");
    cells.get("B3").setValue("Dumont");

    try {
        excel.save("C:\\Users\\User\\Desktop\\Book3.xlsx");
        logger.info("Done !");
    } catch (Exception e) {
        logger.info(e.getMessage());
    }
}

}

@Luca_Macdonald,

Your code is not right. For example, see your line of code:
firstWorksheet.setName(“Test”);

Every time you load your file you add a new sheet with the same name. You cannot add a sheet with the same name in the workbook, sheet name should be unique in the workbook.

Moreover, the following line has no usage for your scenario as you are always adding new sheet to insert data into same set of cells and do not use an existing sheet.

Please fix your code and it will work fine.

Let us know if you still find any issue.