Reputation: 1
` class A {
private HSSFWorkbook workbook;
public A() {
workbook = new HSSFWorkbook();
}
public void method1() {
workbook.createSheet("Sheet1");
System.out.println(" No of sheets: " + workbook.getNumberOfSheets());
method2();
}
public void method2() {
System.out.println(" No of sheets: " + workbook.getNumberOfSheets());
}
}
In the above code i m creating workbook object in constructor... and creating a "Sheet1" in method1 and its printing No of sheets: 1 in method1 but in method2 the No of sheets: 0... Why the same workbook object behaves differently in different methods.. Pls some one help me...
Upvotes: 0
Views: 56
Reputation: 4572
I created some times ago also a Class MyWorkbook
where i was able to add new Sheet
s , i shorten the following code to show only the two Methods which add the first and all the other Sheet
s
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class MyWorkbook {
private final HSSFWorkbook workbook;
public MyWorkbook() {
this.workbook = new HSSFWorkbook();
}
public void createNewSheet() {
workbook.createSheet("Sheet1");
printNumberOfSheets(workbook);
// here i add the second sheet
createAnotherSheet();
}
public void createAnotherSheet() {
workbook.createSheet();
printNumberOfSheets(workbook);
}
private void printNumberOfSheets(final HSSFWorkbook workbook) {
System.out.println("This workbook contains of " + (workbook.getNumberOfSheets() > 1 ? + workbook.getNumberOfSheets() + " Sheets" : workbook.getNumberOfSheets() + " Sheet"));
}
public HSSFWorkbook getWorkbook() {
return workbook;
}
public static void main(String[] args) {
MyWorkbook mw = new MyWorkbook();
mw.createNewSheet();
// workbook contains only 1 sheet
mw.printNumberOfSheets(mw.getWorkbook());
// here i add the 3rd sheet
mw.createAnotherSheet();
// now our workbook contains of 3 sheets
mw.printNumberOfSheets(mw.getWorkbook());
}
}
Patrick
Upvotes: 1