为什么此代码生成无效的Excel文件?

时间:2010-10-06 08:12:16

标签: java excel

这会创建一个excel文件,当尝试处理它时,文件格式无效错误,而不是添加了数字的正确excel文件:

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

我做错了什么?

2 个答案:

答案 0 :(得分:4)

您没有在工作簿上写任何内容。你错过了

  

seurm.write()

关闭工作簿之前

  

seurw.close();

以下是工作代码。

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

}

答案 1 :(得分:-2)

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

必须是

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