Home » excel » java – Why is this code producing an invalid Excel file?

java – Why is this code producing an invalid Excel file?

Posted by: admin April 23, 2020 Leave a comment

Questions:

This creates a excel file which gives file format is not valid error when trying to handle it, not proper excel file with a number added on it:

public static void write () throws IOException, WriteException { 
  WorkbookSettings settings = new WorkbookSettings(); 
  File seurantaraportti = new File("ta.xls"); 
  WritableWorkbook seurw = Workbook.createWorkbook(ta,settings); 
  seurw.createSheet("ta", 0); 
  WritableSheet ws = seurw.getSheet(0); 
  addNumber(ws,0,0,100.0); 
  seurw.close(); 
} 

private static void addNumber(WritableSheet sheet, int column, int row, Double d) 
    throws WriteException, RowsExceededException { 
  Number number=new Number(column, row,d); 
  sheet.addCell(number); 
} 

What am I doing wrong?

How to&Answers:

You are not writing anything to the workbook. you are missing

seurm.write()

before closing the workbook

seurw.close();

Below is the working code.

import java.io.File;
import java.io.IOException;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class WriteExcel {

    public static void write() throws IOException, WriteException {
        WorkbookSettings settings = new WorkbookSettings();
        // settings.setLocale(new Locale("en", "EN"));
        File ta = new File("ta.xls");
        WritableWorkbook seurw = Workbook.createWorkbook(ta, settings);
        seurw.createSheet("ta", 0);
        WritableSheet ws = seurw.getSheet(0);
        addNumber(ws, 0, 0, 100.0);
        seurw.write(); // You missed this line.
        seurw.close();
    }

    private static void addNumber(WritableSheet sheet, int column, int row,
            Double d) throws WriteException, RowsExceededException {
        Number number = new Number(column, row, d);
        sheet.addCell(number);
    }

    public static void main(String[] args) {
        try {
            write();
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Answer:

writableWorkbook seurw = Workbook.createWorkbook(ta,settings);

must be

writableWorkbook seurw = Workbook.createWorkbook(“ta”,settings);