当我重复运行此代码时 - 除了第一次,即使文件已经存在,也会抛出空指针异常。
static public class writeexcel {
public void write(){
try{
File f = new File("C:/Users/acer/Desktop/2.xls");
Workbook existingbook=null;
WritableWorkbook ww;
WritableSheet sr;
if(!f.exists()){
ww = Workbook.createWorkbook(f);
sr = ww.createSheet("mysheet", 0);
}else{
existingbook = Workbook.getWorkbook(f);
ww = Workbook.createWorkbook(f, existingbook);
sr = ww.getSheet("Mysheet");
}
Label lb = new Label(0, 0, " success");
Label lb1 = new Label (1,5,"new task");
sr.addCell(lb);
sr.addCell(lb1);
ww.write();
ww.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
writeexcel exl = new writeexcel() ;
exl.write();
}
}
答案 0 :(得分:0)
尝试beloe代码,它将在100个单元格和行中写入“Success”。然后,您可以根据您的要求对其进行修改。
public class Test {
public static void main(final String[] args) {
Test exl = new Test();
exl.write();
}
public void write() {
try {
File f = new File("fileLocation.xls");
Workbook existingbook = null;
WritableWorkbook ww;
WritableSheet sr;
if (!f.exists()) {
ww = Workbook.createWorkbook(f);
sr = ww.createSheet("mysheet", 0);
} else {
existingbook = Workbook.getWorkbook(f);
ww = Workbook.createWorkbook(f, existingbook);
sr = ww.getSheet("Mysheet");
}
for (int i = 0; i < 100; i++) {
for (int x = 0; x < 100; x++) {
Label lb1 = new Label(i + 1, x + 1, "new task");
// Label lb = new Label(i, x, " success");
// sr.addCell(lb);
sr.addCell(lb1);
}
}
ww.write();
ww.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}