javapoi-hssfhssf

How I can read excel file and set value to null


I want to read a excel file and if there is any data then I want to set it to null then start writing to it. This is what I have for setting excel sheet data to null. I able to write successfully but before write I want to set the value null.

FileOutputStream out = null;

try{
            FileInputStream file = new FileInputStream(new File("/test.xls"));
            HSSFWorkbook oldFile = new HSSFWorkbook(file);
            HSSFSheet sheet = oldFile.getSheetAt(0);
            file.close();

            oldFile.write(null);
            outFile.close();

        } catch(Exception e){
            e.printStackTrace();
        }

Solution

  • One easy solution is to delete and create a sheet:

    File destFile = new File("/test.xls");
    FileInputStream fileStream = new FileInputStream(destFile);
    POIFSFileSystem fsPoi = new POIFSFileSystem(fileStream);
    
    HSSFWorkbook workbook = new HSSFWorkbook(fsPoi);
    
    int index = 0;
    
    HSSFSheet sheet = workbook.getSheet("Setup");
    if(sheet != null)   {
        index = workbook.getSheetIndex(sheet);
        workbook.removeSheetAt(index);
    }
    workbook.createSheet("Setup");
    FileOutputStream output = new FileOutputStream(destFile);
    workbook.write(output);
    output.close();