Getting error excel is corrupted while opening the file created with poi api

public static void createworkbook() throws IOException, InvalidFormatException{

    File file = new File("C:\\Workspace\\Selenium_2.53\\src\\InputFiles\\webuyPurchase.xlsx");
    file.createNewFile();
    fileOut = new FileOutputStream(file);

    XSSFWorkbook workbook = new XSSFWorkbook();
    workbook.write(fileOut);
    XSSFSheet spreadsheet = workbook.createSheet("Products");
    String sheetname =  workbook.getSheetAt(0).getSheetName();
    System.out.println(sheetname);
    fileOut.close();
    // workbook.createSheet("Products");
    System.out.println("workbook is created");

}

While executing the above code , File is created successfully , But while opening the file getting error , File is currpted

1 answer

  • answered 2017-01-11 14:22 kiwiwings

    When you've corrected the order of your statements, it should look like this ...
    so it's not necessary to create the file via file.createNewFile() beforehand

    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    
    public class CreateWorkbook {
        public static void main(String args[]) throws IOException {
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet spreadsheet = workbook.createSheet("Products");
            spreadsheet.createRow(0).createCell(0).setCellValue("this is a test");
            FileOutputStream fos = new FileOutputStream("bla.xlsx");
            workbook.write(fos);
            fos.close();
            workbook.close();
        }
    }