Rename worksheet tab

1

I'm having trouble renaming the name of a tab in the Excell file. I am debugging and after it gives the set with 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();
    }
    
asked by anonymous 28.02.2018 / 02:12

1 answer

1

The problem is that you are changing the name of the only tab in memory. You need to call workbook.write to be able 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();

Remembering that InputStream needs to be closed before calling write .

    
28.02.2018 / 22:07