You create 2 workbook objects if the file exists. One of those workbooks doesn't get closed.
If the workbook exists, you read from and write to the same file while the workbook is open. This corrupts the file. Either use the in-place write method (this is a new addition, still in development), or write to a different file location, close the workbook, and shuffle the files around as necessary. On May 8, 2017 07:51, "Aakash Rathod" <[email protected]> wrote: Hi All, I want to add new sheets to existing excel file, but when file doesn't exist it it successfully created and even opens successfully with the data and when i try to add new sheet to this existing file it doesn't throw any error but when i try to open this file it throws error saying "We found a problem with some content in 'filename' ? Do you want us to try to recover..........". Code is pasted below. Please look into it and help me out. import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class FileCheck { public static void main(String[] args) { XSSFWorkbook workbook = new XSSFWorkbook(); String fileName="Trial.xlsx"; File file = new File(fileName); FileOutputStream out; if(!file.exists()){ // This will create new workbook with new sheet if it doesnt exists{ System.out.println("New"); XSSFSheet mySheet = workbook.createSheet("A"); } else{ // This add new sheet to above created workbook try { System.out.println("Old"); XSSFWorkbook myWorkBook = (XSSFWorkbook) WorkbookFactory.create(file); workbook=myWorkBook; XSSFSheet mySheet = (XSSFSheet) workbook.createSheet("B"); } catch (InvalidFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try{ out = new FileOutputStream(fileName,true); workbook.write(out); out.close(); }catch(Exception e){ e.printStackTrace(); } } } Thanks, Aakash Rathod --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
