Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache poi creates Excel file with error

I am making an Excel file Using Apache_poi. This file will be created on the action event of a button in my Swing application. The Excel sheet gets created just fine but, when I open it, I get this error:

The file you are trying to open is in different format than specified by the file extension

and when I open the file it is completely empty.

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        // String personalclass=jComboBox1.getSelectedItem().toString();
        // String ac="academic";
        // FileOutputStream output=new FileOutputStream("D:\\"+personalclass+ac+".xls");
        FileOutputStream output=new FileOutputStream("D:\\workbook.xls");
        Workbook wb=new HSSFWorkbook();
        Sheet sheet =wb.createSheet("Class 1"); 
        Cell cell=sheet.createRow(0).createCell(3);
        cell.setCellValue("Thisisatestofmerging");
        //sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
        output.close();
    }
    catch(Exception e)
    {
    }
}  
like image 382
Sumit Singh Rana Avatar asked Dec 08 '25 09:12

Sumit Singh Rana


1 Answers

You forgot to call write on your Workbook.

Add this line before closing your stream :

      wb.write(output);
like image 128
Jonathan Drapeau Avatar answered Dec 09 '25 22:12

Jonathan Drapeau