开发者

Why is this code producing an invalid Excel file?

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?


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

}


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

must be

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜