Rename worksheet tab

Asked

Viewed 188 times

1

I’m having trouble renaming an Excell file tab. I’m debugging and after it gives the set the new name.. i can see the new name changed in the execution but in practice the file itself is not changed. Someone ?

private static void prepararPlanilha() {
        try {
            final int quantidadeAbas = AppUtils.workbook.getNumberOfSheets();
            boolean possuiSheet = false;
            for (int i = 0; i <= quantidadeAbas; i++) {
                sheet = AppUtils.loadPlanilha(i);
                if (sheet.getSheetName().length() > 2) {
                    AppUtils.workbook.setSheetName(i, sufixo);
                }
                if (sheet.getSheetName().equals(sufixo)) {
                    possuiSheet = true;
                    break;
                }
            }
            if (!possuiSheet) {
                AppUtils.workbook.createSheet(sufixo);
            }
        } catch (Exception e) {
            System.out.println("Planilha inválida");
        }
        AppUtils.closeWorkbook();
    }

1 answer

1


The problem is that you are changing the tab name in memory only. You need to call the workbook.write to write your changes to the file.

Example:

String inputPath = "path";
FileInputStream inputStream = new FileInputStream(inputPath);

XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
workbook.setSheetName(0, "NewName");

inputStream.close();

FileOutputStream outputStream = new FileOutputStream(inputPath);
workbook.write(outputStream);

outputStream.close();
workbook.close();

Recalling that the InputStream needs to be closed before calling the write.

  • That’s exactly what it was. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.