I have to delete some sheets from an Excel File.
I have used the below code to delete the unnecessary sheets from the Excel file.
public static boolean deleteUnnecessarySheets(Workbook workbook,
boolean authorize)
{
if(workbook != null)
{
int noOfSheets = workbook.getNumberOfSheets();
for( int sheetNo = noOfSheets - 1; sheetNo >= 0; sheetNo-- )
{
Sheet sheet = workbook.getSheetAt(sheetNo);
String sheetName = sheet.getSheetName();
if(sheetName.equalsIgnoreCase("User Defined Actions") || sheetName.equalsIgnoreCase("AUTHORIZE"))
{
if(!authorize && sheetName.equalsIgnoreCase("AUTHORIZE"))
{
workbook.removeSheetAt(sheetNo);
}
}
else
{
workbook.removeSheetAt(sheetNo);
}
}
return true;
}
return false;
}
The code successfully deletes the sheets as expected. But on opening the Excel sheet manually I get the following error.
How can I prevent this from happening? Or what am I doing wrong?