javaxssf

XSSFWorkbook overriding the template file


I'm using XSSFWorkbook to create a xlsx file which stores the result of a SQL query with JAVA 8.

This process is done each month so I use a template xslx file template.xslx.

The point it to open the template and save it as new file. It used to work but now the template is also modified and filled with data (it should stay empty with just the column size, the color, the headers ...).

Here is what I do :

ZipSecureFile.setMinInflateRatio(0);
OPCPackage pkg = OPCPackage.open(new File(excelMaquette));      // Template xlsx            
XSSFWorkbook wb = new XSSFWorkbook(pkg);                        // Fichier xlsx

excelFinal += "_"+dateDuJour+".xlsx";

FileOutputStream stream = new FileOutputStream(new File(excelFinal));

XSSFSheet sheet = wb.getSheetAt(0);             

XSSFCellStyle style = wb.createCellStyle();
            
//remplissage du tableau pour la feuille de détail
for (int i = 0 ; i <= nombreLigneResultat ; i++)
{
    XSSFRow row = sheet.createRow((short)i+1);
                
    for (int l = 0; l < nombreColonnes + 1; l ++)
    {
        XSSFCell  cell = row.createCell(l);         
        cell.setCellValue(tab[i][l]);   
        //System.out.println (" xls = " + tab[i][l]);
    }               
}
                
wb.write(stream);
stream.close();
wb.close();

Thanks for you help

EDIT: I tried rewriting and renaming my files but it's still the same... Its bad because, sometimes the new file will have less data than the previous one so the file will display the new and the extra old data :(


Solution

  • Why are you using OPCPackage?

    OPCPackage is opened from the templateFile in READ_WRITE mode. If this will be closed, it will also be saved.

    You can do it this way:

    try (FileInputStream inputStream = new FileInputStream(templateFile);
                FileOutputStream outputStream = new FileOutputStream(new File(finalFile));
                Workbook workbook = new XSSFWorkbook(inputStream)) {
        wb.getSheetAt(0);
    
        /*
         *
         * Your POI related operations.
         *
         */
    
        wb.write(stream);
        outputStream.close();
        wb.close();
    }