jxl寫入excel表格為空
阿新 • • 發佈:2019-02-15
今天要用java建立一個excel,並把解析的資料存放到excel表中,但是表中一直是空,寫不進資料,程式橫看豎看都沒有問題,下面舉一個簡單的例子。關於jxl的使用,請參考此篇文章。
首先引出jxl寫資料為空的例子
public static void main(String[] args) throws IOException, RowsExceededException, WriteException {
/*建立表*/
WritableWorkbook book = Workbook.createWorkbook(new File("E:/MyData/test.xls" ));
/*建立sheet頁*/
WritableSheet sheet = book.createSheet("第一頁", 0);
Person person = new Person();
person.setUserid("11111");
/*把2行5列資料寫入excel,寫的是第一行和第二行*/
for(int i=0; i<2; i++){
for(int j=0; j<5; j++){
sheet.addCell(new Label(j, i, "data" + i + j));
}
}
/*第一次把上面2行5列資料寫入excel*/
book.write(); //1、此地非常重要,千萬不要加
/*繼續把2行5列資料寫入excel,寫的是第三行和第四行*/
for(int i=2; i<4; i++){
for(int j=0; j<5; j++){
sheet.addCell(new Label(j, i, "data" + i + j));
}
}
/*第二次把第三行和第四行資料寫入excel*/
book.write(); //2
book.close();
}
執行程式,excel資料如下
上面示例總共寫了兩批資料,第一次寫入了第一行和第二行的5列資料,然後呼叫了book.write();再當繼續寫入第三行和第四行資料時就已經不管用了,因為當第一次呼叫book.write()後,表示資料已經寫完了,後面新增的資料就不會再寫進去,即使後面又呼叫了book.write()。所以要在呼叫book.write()之前,把資料準備好,然後一次性寫入。正確寫法改成如下:
刪掉第一個book.write()
public static void main(String[] args) throws IOException, RowsExceededException, WriteException {
WritableWorkbook book = Workbook.createWorkbook(new File("E:/MyData/test.xls"));
WritableSheet sheet = book.createSheet("第一頁", 0);
Person person = new Person();
person.setUserid("11111");
for(int i=0; i<2; i++){
for(int j=0; j<5; j++){
sheet.addCell(new Label(j, i, "data" + i + j));
}
}
//book.write();應刪掉此句程式碼
sheet = book.getSheet("第一頁");
for(int i=2; i<4; i++){
for(int j=0; j<5; j++){
sheet.addCell(new Label(j, i, "data" + i + j));
}
}
book.write();
book.close();
}
執行程式,寫入excel資料如下: