gpt4 book ai didi

java - HSSFWorkbook 对象不保留通过不同方法添加到其中的工作表

转载 作者:行者123 更新时间:2023-12-01 12:52:36 24 4
gpt4 key购买 nike

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

在上面的代码中,我在构造函数中创建工作簿对象...并在方法1中创建“Sheet1”及其打印工作表数量:1在方法1中但在方法2中工作表数量:0...为什么同一个工作簿对象在不同的​​方法中表现不同。请有人帮助我...

最佳答案

我前段时间还创建了一个 Class MyWorkbook ,我可以在其中添加新的 Sheet ,我缩短了以下代码以仅显示添加首先和所有其他 Sheet

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

帕特里克

关于java - HSSFWorkbook 对象不保留通过不同方法添加到其中的工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24109239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com