Why does this code create an invalid excel file?

This creates an excel file that gives the file format is not a valid error when trying to process it, and not a valid excel file with the number added:

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?

+3
source share
2 answers

You do not write anything in the book. you are lacking

seurm.write ()

before closing the book

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();
        }
    }

}
+4
source

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

it should be

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

-2
source

Source: https://habr.com/ru/post/1768188/


All Articles